python调用ffmpeg批量转换音频flac、mp3、m4a

ffmpeg 使用说明

查看使用说明:ffmpeg -h

1
2
3
4
5
6
# usage: 
ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...

# options:
-ab: -ab bitrate audio bitrate (please use -b:a)
-y: overwrite output files

转换命令如下:

1
ffmpeg -i xxx.flac -ab 320k xxx.mp3 -y'

这次我们用到的主要是 -ab 命令,用来指定音频转换的比特率,常见的有: 192K, 320K 等。

遍历文件夹中的所有音频文件, 将 flac 转为 mp3 或 m4a

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import os
import subprocess

path = '~/music/FLAC/'

str = 'ffmpeg -i "{}" -ab 320k "{}" -y'

for parent, dirnames, filenames in os.walk(path):
for filename in filenames:
old_dir = os.path.join(parent, filename)
if old_dir[-4:] == 'flac':
new_dir = old_dir.replace('.flac', '.mp3')
new_dir = old_dir.replace('.flac', '.m4a')
str_cmd = str.format(old_dir, new_dir)
print(str_cmd)

p = subprocess.Popen(str_cmd, shell=True, stdout=subprocess.PIPE)
for line in iter(p.stdout.readline, b''):
print(line.strip().decode('gbk'))

删除原有的 flac 文件

1
2
3
4
5
6
7
8
9
10
11
12
import os
import subprocess

path = '~/music/FLAC/'

for parent, dirnames, filenames in os.walk(path):
for filename in filenames:
old_dir = os.path.join(parent, filename)

if old_dir[-4:] == 'flac':
print(old_dir)
os.remove(old_dir)