使用Python把MP4文件批量转换为MP3文件 前提:本地安装ffmpeg,可以选择安装pydub或是moviepy
使用Python调用ffmpeg需要安装ffmpeg-python
使用PyDub 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 import os from pydub import AudioSegment def convert_mp4_to_mp3(directory): for filename in os.listdir(directory): if filename.endswith('.mp4'): mp4_file_path = os.path.join(directory, filename) mp3_file_path = os.path.splitext(mp4_file_path)[0] + '.mp3' try: # 使用 pydub 转换 mp4 为 mp3 audio = AudioSegment.from_file(mp4_file_path, format='mp4') audio.export(mp3_file_path, format='mp3') # 删除原有的 mp4 文件 os.remove(mp4_file_path) print(f"Converted {mp4_file_path} to {mp3_file_path} and deleted original mp4 file.") except Exception as e: print(f"Error processing {mp4_file_path}: {e}") # 设置你的目标目录 target_directory = r'E:\Entertainment\100s' convert_mp4_to_mp3(target_directory) 使用MoviePy 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 import os from moviepy.editor import VideoFileClip def convert_mp4_to_mp3(directory): # 遍历目录 for filename in os.listdir(directory): if filename.endswith('.mp4'): mp4_file_path = os.path.join(directory, filename) mp3_file_path = os.path.splitext(mp4_file_path)[0] + '.mp3' try: # 使用 moviepy 转换视频为音频 video_clip = VideoFileClip(mp4_file_path) video_clip.audio.write_audiofile(mp3_file_path) video_clip.close() # 删除原有的 mp4 文件 os.remove(mp4_file_path) print(f"Converted {mp4_file_path} to {mp3_file_path} and deleted original mp4 file.") except Exception as e: print(f"Error processing {mp4_file_path}: {e}") # 设置你的目标目录 target_directory = r'E:\Entertainment\北流嘉措' convert_mp4_to_mp3(target_directory) 【最新】windows电脑FFmpeg安装教程手把手详解 windows电脑FFmpeg安装教程手把手详解教程来源
...