Files
songyi/fileconvert.py
2025-04-16 09:38:48 +08:00

67 lines
2.2 KiB
Python
Raw Permalink 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.
import logging
import os
import subprocess
from logging.handlers import RotatingFileHandler
# 配置日志
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(), # 控制台日志
RotatingFileHandler('app.log', maxBytes=1024 * 1024 * 5, backupCount=3) # 日志文件
])
def mp4_to_wav(mp4_file):
try:
mp4_dir = os.path.dirname(mp4_file)
mp4_filename = os.path.splitext(os.path.basename(mp4_file))[0]
wav_file = os.path.join(mp4_dir, f"{mp4_filename}.wav")
command = [
'ffmpeg',
'-y',
'-i', mp4_file,
'-vn', # 去除视频流
'-acodec', 'pcm_s16le', # 使用 PCM 16 位有符号小端编码
'-ar', '44100', # 设置采样率为 44100 Hz
'-ac', '2', # 设置声道数为 2立体声
wav_file
]
subprocess.run(command, check=True)
logging.info(f"成功将 {mp4_file} 转换为 {wav_file}")
return wav_file
except subprocess.CalledProcessError as e:
logging.error(f"转换失败: {e}")
return None
except FileNotFoundError:
logging.error("未找到 FFmpeg请确保已安装并配置好 FFmpeg 环境。")
return None
def mp4_to_mp3(mp4_file):
try:
mp4_dir = os.path.dirname(mp4_file)
mp4_filename = os.path.splitext(os.path.basename(mp4_file))[0]
mp3_file = os.path.join(mp4_dir, f"{mp4_filename}.mp3")
command = [
'ffmpeg',
'-y',
'-i', mp4_file,
'-vn', # 去除视频流
mp3_file
]
print(command)
subprocess.run(command, check=True)
logging.info(f"成功将 {mp4_file} 转换为 {mp3_file}")
return mp3_file
except subprocess.CalledProcessError as e:
logging.error(f"转换失败: {e}")
return None
except FileNotFoundError:
logging.error("未找到 FFmpeg请确保已安装并配置好 FFmpeg 环境。")
return None