Python中音频处理库pydub的使用教程

yipeiwu_com6年前Python基础

前言

pydub是Python中用户处理音频文件的一个库。本文主要介绍了关于Python音频处理库pydub使用的相关内容,分享出来供大家参考学习,下面来看看详细的介绍:

安装:

  1、安装pip工具:sudo apt-get install python-pip

  2、安装pydub:sudo pip install pydub

  3、pydub依赖于ffmpeg,所以还需要安装ffmpeg,由于Ubunbtu14.04官方源移除了ffmpeg,因此通过ppa源安装:

 sudo apt-add-repository ppa:mc3man/trusty-media
 sudo apt-get update
 sudo apt-get install ffmpeg

使用:

AudioSegment方法能够将一个音频文件打开成AudioSegment示例,并使用各种方法处理音频,使用前先调用from pydub import AudioSegment

打开音频:

sound1 = AudioSegment.from_file("/path/to/sound.wav", format="wav") //默认mp3格式

sound2 = AudioSegment.from_file("/path/to/another_sound.mp3", format="mp3")等价于sound1
 = AudioSegment.from_mp3("/path/to/sound.mp3")

音量处理:

louder = sound1 + 6 //sound1 声音提高6dB

quieter = sound1 - 6 //sound1 声音降低6dB

combined = sound1 + sound2  //sound1 和sound2叠加

duration_in_milliseconds = len(sound1)  //获取sound的时长

beginning = sound1[:5000] //获取sound1的前5秒音频数据

end = sound1[-5000:]  //获取sound1的后5秒音频数据

注意:

1、对于多个音频的计算,需要多个音频之间的通道数、帧数、采样率以及比特数都一样,否则低质量的音频会向高质量的转换,单声道会向立体声转换,低帧数向高帧数转换。

2、AudioSegment原生就支持wav和raw,如果其他文件需要安装ffmpeg。raw还需要,sample_width,frame_rate,channels三个参数。

生成文件:

export()方法可以使一个AudioSegment对象转化成一个文件。

sound = AudioSegment.from_file("/path/to/sound.wav", format="wav") 

file_handle = sound.export("/path/to/output.mp3", format="mp3")  //简单输出

file_handle = sound.export("/path/to/output.mp3", 
       format="mp3",
       bitrate="192k",
       tags={"album": "The Bends", "artist": "Radiohead"})   //复杂输出

AudioSegment.empty():

AudioSegment.empty()用于生成一个长度为0的AudioSegment对象,一般用于多个音频的合并。

sounds = [
 AudioSegment.from_wav("sound1.wav"), 
 AudioSegment.from_wav("sound2.wav"), 
 AudioSegment.from_wav("sound3.wav"), 
]
playlist = AudioSegment.empty()
for sound in sounds:
 playlist += sound

AudioSegment.silent():

ten_second_silence = AudioSegment.silent(duration=10000) //产生一个持续时间为10s的无声AudioSegment对象

获取参数:

此外,还能通过AudioSegment获取音频的参数,同时还能修改原始参数。

具体详见:https://github.com/jiaaro/pydub/blob/master/API.markdown

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

编写Python脚本把sqlAlchemy对象转换成dict的教程

在用sqlAlchemy写web应用的时候,经常会用json进行通信,跟json最接近的对象就是dict,有时候操作dict也会比操作ORM对象更为方便,毕竟不用管数据库session的...

使用Python读写及压缩和解压缩文件的示例

读写文件 首先看一个例子: f = open('thefile.txt','w') #以写方式打开, try: f.write('wokao') finally: f.c...

运用Python的webbrowser实现定时打开特定网页

运用webbrowser库中的一个函数实现自动打开浏览器: webbrowser.open(http://blog.csdn.net/arescnzj) 运用time库中的函数获取...

关于tf.nn.dynamic_rnn返回值详解

关于tf.nn.dynamic_rnn返回值详解

函数原型 tf.nn.dynamic_rnn( cell, inputs, sequence_length=None, initial_state=None, d...

在Python的Django框架中使用通用视图的方法

使用通用视图的方法是在URLconf文件中创建配置字典,然后把这些字典作为URLconf元组的第三个成员。 例如,下面是一个呈现静态“关于”页面的URLconf: from djan...