如果目录中还包含.mp3
格式的音频文件,并且你希望对它们进行处理,你可以使用pydub
库来截取音频的前20秒。以下是如何修改之前的脚本以支持.mp3
文件:
首先,确保安装了pydub
和ffmpeg
:
pip install pydub
ffmpeg
是一个强大的多媒体框架,pydub
依赖它来处理媒体文件。你可以从FFmpeg官网下载并安装。
更新脚本如下:
import os from moviepy.editor import VideoFileClip from pydub import AudioSegment def clip_video(video_path, output_path, duration=20): clip = VideoFileClip(video_path).subclip(0, duration) clip.write_videofile(output_path, codec='libx264') def clip_audio(audio_path, output_path, duration=20): audio = AudioSegment.from_file(audio_path) # 截取音频前duration秒 if len(audio) > duration * 1000: # 将秒转换为毫秒 clip = audio[:duration * 1000] else: clip = audio # 导出截取的音频 clip.export(output_path, format="mp3") def main(directory): output_dir = os.path.join(directory, '20s') if not os.path.exists(output_dir): os.makedirs(output_dir) for filename in os.listdir(directory): if filename.endswith(('.mp4', '.avi', '.mov', '.mkv')): video_path = os.path.join(directory, filename) output_path = os.path.join(output_dir, filename) print(f"Processing video {filename}...") clip_video(video_path, output_path) elif filename.endswith('.mp3'): audio_path = os.path.join(directory, filename) output_path = os.path.join(output_dir, filename) print(f"Processing audio {filename}...") clip_audio(audio_path, output_path) if __name__ == "__main__": directory = 'path_to_your_media_directory' # 替换为你的媒体文件目录 main(directory)