pydub音频处理库使用详解

pydub简介

pydub是基于ffmpeg,有关ffmpeg的介绍,可以看下百度百科,windows下安装完ffmpeg之后配置其bin目录到PATH

pydub使用

1
2
3
4
5
6
7
8
9
10
from pydub import AudioSegment
song = AudioSegment.from_wav("never_gonna_give_you_up.wav")
song = AudioSegment.from_mp3("never_gonna_give_you_up.mp3")
ogg_version = AudioSegment.from_ogg("never_gonna_give_you_up.ogg")
flv_version = AudioSegment.from_flv("never_gonna_give_you_up.flv")
mp4_version = AudioSegment.from_file("never_gonna_give_you_up.mp4", "mp4")
wma_version = AudioSegment.from_file("never_gonna_give_you_up.wma", "wma")
aac_version = AudioSegment.from_file("never_gonna_give_you_up.aiff", "aac")

通过以上方法可以从不同格式的音频和视频文件中获取AudioSegment对象,进而对其进行一系列处理

Slice audio

1
2
3
4
5
6
# pydub does things in milliseconds
ten_seconds = 10 * 1000
first_10_seconds = song[:ten_seconds]
last_5_seconds = song[-5000:]

Make the beginning louder and the end quieter

1
2
3
4
5
# boost volume by 6dB
beginning = first_10_seconds + 6
# reduce volume by 3dB
end = last_5_seconds - 3

Concatenate audio (add one file to the end of another)

1
without_the_middle = beginning + end

AudioSegments are immutable

1
2
# song is not modified
backwards = song.reverse()

将获取一个新的AudioSegment对象

Save the results (again whatever ffmpeg supports)

1
2
3
awesome.export("mashup.mp3", format="mp3")
awesome.export("mashup.mp3", format="mp3", tags={'artist': 'Various artists', 'album': 'Best of 2011', 'comments': 'This album is awesome!'})
awesome.export("mashup.mp3", format="mp3", bitrate="192k")

例子

将目录下的所有mp4文件和flv文件转换为mp3

1
2
3
4
5
6
7
8
9
10
11
12
import os
import glob
from pydub import AudioSegment
video_dir = '/home/johndoe/downloaded_videos/' # Path where the videos are located
extension_list = ('*.mp4', '*.flv')
os.chdir(video_dir) # change the workplace
for extension in extension_list:
for video in glob.glob(extension):
mp3_filename = os.path.splitext(os.path.basename(video))[0] + '.mp3'
AudioSegment.from_file(video).export(mp3_filename, format='mp3')

参考文档

坚持原创技术分享,您的支持将鼓励我继续创作!