You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import subprocess
from pathlib import Path
def convert_mp4_to_wav(
input_mp4: str,
ffmpeg_path: str = r"d:\ffmpeg\ffmpeg.exe",
output_path: str = None # 新增输出路径参数
):
"""
将指定MP4文件转换为WAV格式
参数:
input_mp4 - 输入的MP4文件路径
ffmpeg_path - FFmpeg可执行文件路径
output_path - 可选输出路径(可指定完整路径或目录)
"""
input_path = Path(input_mp4)
# 处理输出路径逻辑
if output_path:
output_path = Path(output_path)
if output_path.is_dir(): # 如果传入的是目录
output_path = output_path / f"{input_path.stem}.wav"
output_path.parent.mkdir(parents=True, exist_ok=True)
else:
# 默认输出到wav目录
output_dir = Path("wav")
output_dir.mkdir(exist_ok=True)
output_path = output_dir / f"{input_path.stem}.wav"
cmd = [
ffmpeg_path,
"-i", str(input_path),
"-acodec", "pcm_s16le",
"-ac", "1",
"-ar", "16000",
"-y",
str(output_path) # 使用处理后的输出路径
]
try:
# 执行转换命令
subprocess.run(cmd, check=True, capture_output=True)
print(f"转换成功:{input_path} -> {output_path}")
except subprocess.CalledProcessError as e:
print(f"转换失败:{e.stderr.decode('gbk')}")
except FileNotFoundError:
print(f"FFmpeg未找到请确认路径是否正确{ffmpeg_path}")