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!'})
  • 播放音频

长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn