FFmpeg结合python3来实现对视频文件中的音频流和视频流的批量提取和保存

实现环境为Ubuntu环境下 python3.6.5。

import os
import fnmatch


# get all files
def dir_list(path, allfiles):
    """
    :param path: 文件的路径
    :param allfiles: 存放文件地址的列表
    :return: 返回所有的文件列表
    """
    filelists = os.listdir(path)
    for filename in filelists:
        filepath = os.path.join(path, filename)
        if os.path.isdir(filepath):
            dir_list(filepath, allfiles)
        elif fnmatch.fnmatch(filepath, '*.mp4'):  # 判断文件格式
            allfiles.append(filepath)

    return allfiles


# 分辨率的转换
def RunScript(fileList):
    print('*' * 15 + 'Start to run:')
    """ffmpeg -i 3.mp4 -vn -y -acodec copy 3.aac
       ffmpeg -i 2018.mp4 -codec copy -bsf: h264_mp4toannexb -f h264 tmp.264
       ffmpeg -i killer.mp4 -an -vcodec copy out.h264
    """

    # 分离音频的执行命令前部分    {}{}分别为原始视频  与输出后保存的路径名
    code_yin = 'ffmpeg -i {} -vn -y -acodec copy {}'

    code_video = 'ffmpeg -i {} -an -vcodec copy  {}'  # {}{}分别为原始视频  与输出后保存的h264文件路径名
    # code_Mid = ' -vf scale=480:848 {} -hide_banner'
    for filename in fileList:
        # 视频名称
        input_name = filename.split('.')[0].split('\\')[-1]
        # print(input_name)

        out_video_name = input_name + '.h264'
        out_yin_name = input_name + '.aac'
        # h264视频流的输路径
        out_video_path = os.path.join(New_Save_path, out_video_name)
        out_yinpin_path = os.path.join(New_Save_path, out_yin_name)
        print(out_video_path)
        # 最终执行提取音频的指令
        code_finish_yin = code_yin.format(filename, out_yinpin_path)
        # 提取视频的指令
        code_finish_video = code_video.format(filename, out_video_path)

        print(code_finish_video)

        # print('*'* 20 + finish_code)
        os.system(code_finish_video)
        os.system(code_finish_yin)

    print('End #################')


if __name__ == '__main__':
    global fileDir
    fileDir = r"C:\Users\li841\Desktop\筛选完成视频\change480"
    global New_Save_path
    New_Save_path = r"C:\Users\li841\Desktop\音频与视频分离文件"
    allfile = []
    dir_list(fileDir, allfile)
    RunScript(allfile)

在Windows环境下,如果你安装好了ffmpeg也可以直接使用下面代码直接提取视频流中的音频信息。

ffmpeg -i test.mp4 -vn -y -acodec copy test.aac

若要直接提取视频流中的视频信息,则可以:

ffmpeg -i killer.mp4 -an -vcodec copy out.h264

如有问题敬请指正!

你可能感兴趣的:(FFmpeg学习)