Python3批量将mkv文件转为mp4的函数

Python3批量将mkv文件转为mp4


让GPT生成代码,结果直接把mkv的后缀变为mp4,令人啼笑皆非,所以鼓捣了一个钟,终于封装了可以直接将某文件夹下所有mkv文件转为mp4文件的函数,还是Mark一下吧!

import os
import ffmpy
from pathlib import Path


def convert_mkv_to_mp4(input_dir, output_dir):
    # 创建输出目录
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 遍历输入目录及其子目录
    for root, dirs, files in os.walk(input_dir):
        for file in files:
            # 构建输入文件路径
            input_file = os.path.join(root, file)

            # 打印文件路径和类型
            print(f"Scanning file: {input_file}, Type: {file.split('.')[-1]}")

            if file.endswith('.mkv'):
                # 检查文件是否存在
                if not os.path.exists(input_file):
                    print(f"File not found: {input_file}")
                    continue

                # 构建输出文件路径,保持原有文件夹结构
                relative_path = os.path.relpath(root, input_dir)
                output_subdir = os.path.join(output_dir, relative_path)
                if not os.path.exists(output_subdir):
                    os.makedirs(output_subdir)
                output_file = os.path.join(output_subdir, file.replace('.mkv', '.mp4'))

                # 使用 ffmpy 进行转换
                try:
                    ff = ffmpy.FFmpeg(
                        executable=r'C:\Users\ffmpeg.exe', #显式指定ffmpeg.exe的位置
                        inputs={input_file: None},
                        outputs={output_file: ['-c:v', 'copy', '-c:a', 'copy']}
                    )
                    ff.run()
                    print(f"Converted {input_file} to {output_file}")
                except ffmpy.FFExecutableNotFoundError as e:
                    print(f"FFmpeg executable not found: {e}")
                except ffmpy.FFRuntimeError as e:
                    print(f"Failed to convert {input_file}: {e}")



# 示例用法
input_directory = './digit_mkv'
output_directory = './digit_mp4'
convert_mkv_to_mp4(input_directory, output_directory)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值