python调用ffmpeg处理音频-转换格式

2022-03-15  本文已影响0人  洗洗睡吧i

ffmpeg 使用说明

查看使用说明:ffmpeg -h

# usage: 
ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...

# options:
-ab:                比特率
-vn:                video no
-map_metadata 0:    保留 meta data

-y:    overwrite output files

遍历文件夹中的所有 flac 文件, 转成 mp3 或 aac

# %%
def convert(path='/', ext=''):

    for parent, dirnames, filenames in os.walk(path):
        for filename in filenames:
            extension = os.path.splitext(filename)[1]

            if extension == ext:

                old_dir = os.path.join(parent, filename)
                
                # 转 mp3
                # new_dir = old_dir.replace('.flac', '.mp3')
                # ffmpeg_command = f'ffmpeg -i "{old_dir}" -ab 320k -map_metadata 0 "{new_dir}" -y'
                
                # 转 aac
                new_dir = old_dir.replace('.flac', '.m4a')
                # ffmpeg_command = f'ffmpeg -i "{old_dir}" -ab 320k -vn "{new_dir}" -y'
                ffmpeg_command = f'ffmpeg -i "{old_dir}" "{new_dir}" -y'
                
                p = subprocess.Popen(ffmpeg_command, shell=True, stdout=subprocess.PIPE)
                for line in iter(p.stdout.readline, b''):
                    msg = line.strip().decode('gbk')
                    print(msg)


convert(os.getcwd(), ext='.flac')

# %%
import os
import subprocess


def remove(path='/', ext=''):

    for parent, dirnames, filenames in os.walk(path):
        for filename in filenames:
            extension = os.path.splitext(filename)[1]

            if extension == ext:
                dir = os.path.join(parent, filename)

                print(dir)
                os.remove(dir)


# remove(os.getcwd(), ext='.flac')

上一篇下一篇

猜你喜欢

热点阅读