pydub音频处理库的使用

pydub音频处理库的使用

在使用pydub这个模块之前应确保你的libav或者FFmpeg

  • Mac上安装libav或FFmpeg

brew install libav --with-libvorbis --with-sdl --with-theora # 安装libav
brew install ffmpeg --with-libvorbis --with-sdl2 --with-theora # 安装ffmpeg
  • Linux(使用apt 安装)
apt-get install libav-tools libavcodec-extra # libav
apt-get install ffmpeg libavcodec-extra # ffmpeg

模块的使用

  • 安装模块
pip install pydub
  • 打开文件

  

from pydub import AudioSegment

wav_file = AudioSegment.for_wav("filepath") # 读取wav文件
mp3_file = AudioSegment.for_mp3("filepath") # 读取mp3文件
ogg_file = AudioSegment.for_ogg("filepath") # 读取ogg文件
flv_file = AudioSegment.for_flv("filepath") # 读取flv文件
mp4_file = AudioSegment.for_file("filepath") # 读取mp4文件
m4a_file = AudioSegment.for_file("filepath") # 读取m4a文件
# 使用for_file可以获取其他ffmpeg支持的其他音频格式
  • 对音频进行切片
ten_seconds = 10 * 1000
first_10_seconds = wav_file[:ten_seconds] # 前10秒
last_5_seconds = wav_file[-5000:] # 后5秒
  • 音量调节
beginning = first_10_seconds + 6 # 增加6dB
end = last_5_seconds - 3 # 降低3dB
  • 拼接音频
without_the_middle = beginning + end
  • 获取音频长度
without_the_middle.duration_seconds # 获取音频长度(浮点型)
  • 音频反转
backwards = wav_file.reverse()
  • 淡入
with_style = beginning.append(end,crossfade=1500)
  • 重复
do_it_over = with_style * 2
  • 淡出
awesome = do_it_over.fade_in(2000).fade_out(3000)
  • 保存
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!'})
  • 播放音频
from pydub.playback import play
sound = AudioSegment.from_file("test.wav")
play(sound)

  

原文地址:https://www.cnblogs.com/jiayunlong/p/11979183.html