64 lines
1.9 KiB
Python
64 lines
1.9 KiB
Python
import os
|
|
from moviepy.editor import VideoFileClip
|
|
|
|
def mp4_to_wav(input_file, output_file):
|
|
"""
|
|
将MP4文件转换为WAV格式
|
|
|
|
:param input_file: 输入的MP4文件路径
|
|
:param output_file: 输出的WAV文件路径
|
|
"""
|
|
try:
|
|
# 加载视频文件
|
|
video = VideoFileClip(input_file)
|
|
|
|
# 提取音频
|
|
audio = video.audio
|
|
|
|
# 将音频写入WAV文件
|
|
audio.write_audiofile(output_file)
|
|
|
|
# 关闭视频和音频对象
|
|
audio.close()
|
|
video.close()
|
|
|
|
print(f"转换成功: {input_file} -> {output_file}")
|
|
except Exception as e:
|
|
print(f"转换失败: {input_file} - {str(e)}")
|
|
|
|
def process_directory(directory):
|
|
"""
|
|
处理目录中的所有MP4文件
|
|
|
|
:param directory: 包含MP4文件的目录路径
|
|
"""
|
|
for filename in os.listdir(directory):
|
|
if filename.lower().endswith('.mp4'):
|
|
input_file = os.path.join(directory, filename)
|
|
output_file = os.path.splitext(input_file)[0] + ".wav"
|
|
mp4_to_wav(input_file, output_file)
|
|
|
|
def main():
|
|
# 获取输入路径
|
|
input_path = input("请输入MP4文件或包含MP4文件的目录路径: ").strip()
|
|
|
|
# 检查输入路径是否存在
|
|
if not os.path.exists(input_path):
|
|
print("错误: 输入路径不存在")
|
|
return
|
|
|
|
# 判断输入路径是文件还是目录
|
|
if os.path.isfile(input_path):
|
|
if not input_path.lower().endswith('.mp4'):
|
|
print("错误: 输入文件不是MP4格式")
|
|
return
|
|
output_file = os.path.splitext(input_path)[0] + ".wav"
|
|
mp4_to_wav(input_path, output_file)
|
|
elif os.path.isdir(input_path):
|
|
process_directory(input_path)
|
|
else:
|
|
print("错误: 输入路径既不是文件也不是目录")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|