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)

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM