python ffmpeg 批量转格式

import os
import subprocess

def flac_to_wav(source_dir, target_dir):
    # 遍历源目录及其子目录
    for root, dirs, files in os.walk(source_dir):
        # 以LibriSpeech为例
        # data/LibriSpeech-flac ['train-clean-360','dev-clean','dev-clean'] []
        # data/LibriSpeech-flactrain-clean-360 ['14','16','17'...] []
        # data/LibriSpeech-flac/train-clean-360/14 ['208','212'] []
        # data/LibriSpeech-flac/train-clean-360/14/208 [] [所有文件名]。再返回上级
        # data/LibriSpeech-flac/train-clean-360/14/212 [] [所有文件名].再返回上级
        # data/LibriSpeech-flac/train-clean-360/16 ['122827','122828'] []
        # 一直这样下去
        # 遍历一个文件夹的子文件夹,直到某一个文件夹所有文件被遍历完,再返回上级,也就是每次都要求dirs为空

        # 计算目标目录中对应的子目录路径
        relative_path = os.path.relpath(root, source_dir)
        target_sub_dir = os.path.join(target_dir, relative_path)
        # 创建目标子目录(如果不存在)
        if not os.path.exists(target_sub_dir):
            os.makedirs(target_sub_dir)

        # 遍历当前目录下的所有文件
        for file in files:
            if file.endswith('.flac'):
                # 构建源文件和目标文件的完整路径
                flac_file_path = os.path.join(root, file)
                wav_file_name = os.path.splitext(file)[0] + '.wav'
                wav_file_path = os.path.join(target_sub_dir, wav_file_name)

                try:
                    # 执行 FFmpeg 命令进行转换
                    subprocess.run(['ffmpeg', '-i', flac_file_path, wav_file_path], check=True)
                    print(f"Successfully converted {flac_file_path} to {wav_file_path}")
                except subprocess.CalledProcessError as e:
                    print(f"Error converting {flac_file_path}: {e}")
                except FileNotFoundError:
                    print("FFmpeg not found. Please make sure FFmpeg is installed and added to the system's PATH.")


# 替换为你的 LibriSpeech 数据集的源目录
source_dir = './1'
# 替换为你想要保存转换后文件的目标目录,不用新建
target_dir = './2'

flac_to_wav(source_dir, target_dir)

本文作者:vanxkr

本文链接:http://www.vanxkr.com/2025/4/python-ffmpeg

版权声明:本博客所有文章除特别声明外,均采用CC BY-NC-SA 3.0许可协议。转载请注明出处!

python 笔记
0 条评论
已登录,注销 取消