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

ffmpeg 使用说明

查看使用说明:ffmpeg -h

1
2
3
4
5
6
7
8
9
# 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# %%
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')