from pathlib import Path from moviepy.editor import * import sys # print('argv[1]:' + str(sys.argv[1])) import os from pydub import AudioSegment def mp4_to_mp3(mp4_uri): # Load the mp4 file video = VideoFileClip(mp4_uri) # Extract audio from video mp3_uri = mp4_uri + ".mp3" video.audio.write_audiofile(mp3_uri) return mp3_uri def audio_to_wav(wav_uri, out_sample_rate=16000): src = wav_uri dst = wav_uri + ".wav" if os.path.exists(dst): os.remove(dst) # convert wav to mp3 sound = AudioSegment.from_file(src) sound = sound.set_frame_rate(out_sample_rate) sound.export(dst, format="wav") print(' audio_to_wav: ', str(dst)) return dst def wav_to_mp3(wav_uri): mp3_uri = wav_uri + '.mp3' AudioSegment.from_wav(wav_uri).export(mp3_uri, format='mp3') return mp3_uri # def wav_to_mp3_bitrate(wav_uri, bitrate): # mp3_uri = wav_uri + '.mp3' # AudioSegment.from_wav(wav_uri).export(mp3_uri, format='mp3', bitrate=bitrate) # return mp3_uri # 处理命令行 if __name__ == "__main__": # 获取命令行参数 if len(sys.argv) < 2: print("用法:python to_mp3.py <文件或通配符>") sys.exit(1) # 处理文件或通配符参数 bitrate = -1 if len(sys.argv) > 2: bitrate = sys.argv[2] for input_file in sys.argv[1:]: # print("input_file:" + str(input_file)) # input_files.extend(Path().glob(input_file)) if input_file.lower().endswith(".wav"): res = wav_to_mp3(str(input_file)) print(res) elif input_file.lower().endswith(".mp4"): res = mp4_to_mp3(str(input_file)) print(res) # # 转换每个文件为 MP3 文件 # for input_file in input_files: # if input_file.suffix.lower() == ".wav": # res = wav_to_mp3(str(input_file)) # print(res) # elif input_file.suffix.lower() == ".mp4": # res = mp4_to_mp3(str(input_file)) # print(res)