unified_python/tts/多mp3文件合并.py
2025-08-06 17:26:07 +08:00

63 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from pydub import AudioSegment
import os
# 使用相对路径
AudioSegment.converter = "ffmpeg.exe"
AudioSegment.ffmpeg = "ffmpeg.exe"
AudioSegment.ffprobe = "ffprobe.exe"
# 验证文件是否存在
ffmpeg_path = os.path.join(os.path.dirname(__file__), "ffmpeg.exe")
ffprobe_path = os.path.join(os.path.dirname(__file__), "ffprobe.exe")
if not os.path.exists(ffmpeg_path):
raise FileNotFoundError(f"请将ffmpeg.exe放在项目目录中: {ffmpeg_path}")
if not os.path.exists(ffprobe_path):
raise FileNotFoundError(f"请将ffprobe.exe放在项目目录中: {ffprobe_path}")
def merge_mp3_files(input_directory, output_file):
"""
将指定目录下的所有MP3文件合并成一个MP3文件
Args:
input_directory (str): 包含MP3文件的目录路径
output_file (str): 输出的合并后MP3文件路径
"""
# 获取目录下所有mp3文件
mp3_files = []
for file_name in os.listdir(input_directory):
if file_name.lower().endswith('.mp3'):
mp3_files.append(os.path.join(input_directory, file_name))
# 按文件名字母顺序排序,确保合并顺序一致
mp3_files.sort()
if not mp3_files:
print("目录中没有找到MP3文件")
return
print(f"找到 {len(mp3_files)} 个MP3文件开始合并...")
# 加载第一个音频文件
combined = AudioSegment.from_mp3(mp3_files[0])
print(f"已加载: {os.path.basename(mp3_files[0])}")
# 依次合并其余的音频文件
for file_path in mp3_files[1:]:
audio = AudioSegment.from_mp3(file_path)
combined += audio # 使用 += 操作符合并音频
print(f"已合并: {os.path.basename(file_path)}")
# 导出合并后的音频文件
combined.export(output_file, format="mp3")
print(f"所有文件已合并完成,输出文件: {output_file}")
# 使用示例
if __name__ == "__main__":
input_dir = "./马保国语音包"
output_file = "./马保国语音包_合并.mp3"
merge_mp3_files(input_dir, output_file)