复制代码- # 作者:浮霄默客
- # 日期:2024.4.7
- # 描述:交换音频左右声道
- import os # 导入os库,用于操作系统相关操作,如文件和目录操作
- import subprocess # 导入subprocess库,用于创建新的进程,连接到其输入/输出/错误管道,并获取其返回码
- # 获取当前脚本所在目录
- script_dir = os.path.dirname(os.path.abspath(__file__))
- ffmpeg_path = os.path.join(script_dir, 'ffmpeg.exe')
- # 定义一个列表,包含所有支持的音频格式
- supported_formats = ['mp3', 'wav', 'flac', 'aac', 'MP3', 'WAV', 'FLAC', 'ACC']
- def get_bitrate(audio_file):
- # 使用ffmpeg获取比特率
- # 定义ffmpeg命令行参数
- cmd = [ffmpeg_path, '-i', audio_file, '-f', 'null', '-']
- # 执行命令,获取执行结果
- result = subprocess.run(cmd, stderr=subprocess.PIPE, text=True, encoding='utf-8', errors='ignore')
- # 将结果按行分割
- lines = result.stderr.split('\n')
- # 遍历每一行
- for line in lines:
- # 如果行中包含"bitrate"
- if "bitrate" in line:
- # 将行按空格分割,得到每个部分
- bitrate_info = line.split(' ')
- # 遍历每个部分
- for i, info in enumerate(bitrate_info):
- # 如果部分是"bitrate:"
- if info == "bitrate:":
- # 返回下一个部分,即比特率值,加上"k"作为单位
- return bitrate_info[i + 1] + "k" # 假设比特率单位为kbps
- # 如果没有找到"bitrate:",则返回默认比特率"128k"
- return "128k" # 默认比特率
- def get_codec(audio_file):
- # 使用 ffmpeg 获取音频文件的信息
- cmd = [ffmpeg_path, '-i', audio_file]
- result = subprocess.run(cmd, stderr=subprocess.PIPE, text=True, encoding='utf-8', errors='ignore')
-
- # 从输出中解析编解码器信息
- lines = result.stderr.split('\n')
- for line in lines:
- if 'Stream #0:0' in line and 'Audio' in line:
- codec_index = line.find('Audio: ')
- if codec_index != -1:
- codec_info = line[codec_index + len('Audio: '):].split(',')[0].split()[0]
- return codec_info.strip()
-
- return None
- def swap_and_export_with_ffmpeg(input_file, output_file, bitrate, codec):
- # 构建ffmpeg命令,用于交换声道并设置比特率
- cmd = [
- ffmpeg_path, # 调用ffmpeg
- '-i', input_file, # 指定输入文件
- '-acodec', codec, # 指定音频编解码器
- '-ac', '2', # 确保输出为双声道
- '-map_channel', '0.0.1', '-map_channel', '0.0.0', # 交换声道
- '-b:a', bitrate, # 设置音频比特率
- output_file # 指定输出文件
- ]
- # 执行命令
- subprocess.run(cmd, check=True)
- # 遍历当前目录下的所有文件
- for filename in os.listdir('.'):
- # 如果文件是支持的音频格式
- if filename.split('.')[-1] in supported_formats:
- # 获取文件的比特率
- bitrate = get_bitrate(filename)
- # 获取文件的编解码器
- codec = get_codec(filename)
- # 使用ffmpeg交换声道并导出
- swap_and_export_with_ffmpeg(filename, '左右反转_' + filename, bitrate, codec)
|