1. AudioSegment库的使用
from pydub import AudioSegment
# 可以看到读取文件有很多方式
# 有直接from_file(),也有from_mp3()、from_wav()
# 下面的两个读取语句是等价的:
sound=AudioSegment.from_file("aaa.mp3","mp3")
sound=AudioSegment.from_mp3("aaa.mp3")
2. 获取音频文件信息
#取得音频的声道数channel_count = sound.channelsprint(channel_count)#取得音频文件采样频率frames_per_second = sound.frame_rateprint(frames_per_second)#取得音频的持续时间,同 len()print(sound.duration_seconds)print((len(sound) / 1000.0))#取得音频数据raw_audio_data = sound.raw_data #这是bytes类型的wav_data=sound.get_array_of_samples() #这是array类型的数据print(raw_audio_data)#取得音频文件帧宽度bytes_per_frame = sound.frame_widthprint(bytes_per_frame)#取得音频中的最大振幅normalized_sound = sound.apply_gain(-sound.max_dBFS)print(normalized_sound)#取得音频的分贝数loudness = sound.dBFSprint(loudness)#获取音频音量大小,该值通常用来计算分贝数(dB= 20×lgX)loudness = sound.rmsprint(loudness)
3. 音频文件修改
# 语音切割,以毫秒为单位
start_time=0
end_time=2000
part = sound[start_time:end_time]
#调整音量大小
louder_via_method = sound.apply_gain(+3.5) # 提高
quieter_via_method = sound.apply_gain(-5.7) # 减小
#调整多声道音频的左右声道音量
#如果单声道音频调用此方法,它将先被转换为多声道
stereo_balance_adjusted = sound.apply_gain_stereo(-6, +2)
#左右声道平衡,按百分比增大一边,减小另一边
# pan the sound 15% to the right
panned_right = sound.pan(+0.15)
# # pan the sound 50% to the left
panned_left = sound.pan(-0.50)
4. 文件保存
#语音文件切割
part = sound[start_time:end_time]
#定义切割文件名称
data_split_filename='save.wav')
#保存切割文件
part.export(data_split_filename, format="wav")
5. AudioSegment中mp3转wav文件并转换采样频率fs
from pydub import AudioSegmentdef mp3_to_wav(mp3_filename,wav_filename,frame_rate):'''调整语音文件的编码 mp3 --> wav:param mp3_filename: mp3文件名称:param wav_filename: wav文件名称:param frame_rate: 采样频率:return:'''mp3_file = AudioSegment.from_mp3(file=mp3_filename)mp3_file.set_frame_rate(frame_rate).export(wav_filename,format="wav")