打开音频文件
Import wave
filePath = “hello.wav”
file = wave.open(filePath, ‘rb’)
或者使用上下文管理器
With contexlib.closing(wave.open(filePath, ‘rb’)) as wf:
Doing something with wf
在执行过程离开with语句体时自动执行object.close()
获得音频参数
Params = file.getparams()
Nchannels, sampwidth, framerate, nframes = params[:4]
其中:Nchannels:声道数;Sampwidth:量化位数,表示使用多少byte来表达一次采样采集的数据
;Framerate:采样频率;Nframes:采样点数。
或者
Nchannels = file.getnchannels()
Sampwidth = file.getsampwidth()
Framerate = file.getframerate()
Nframes = file.getnframes()
读取音频数据
strData = file.readframes(nframes) #读取音频字符串格式
#import numpy as np
waveData = np.frambuffer (strData, dtype = np.int16) #将字符串转化为int
waveData = waveData * 1.0/(max(abs(waveData)))
写入数据到音频文件
File = wave.open(path, ‘wb’)
File.setnchannels(1)
File.setsampwidth(2)
File.setframerate(sample_rate)
File.writeframes(frames)
需要注意的是 data有两种数据格式,int 或者 str,音频文件读取和写入的格式都是str。
所以要注意格式的转换。
格式转换
wave_data = wave_file.readframes(wave_file.getnframes())
wave_data = np.fromstring(wave_data, np.int16)
或者
wave_data = wave_data.astype(np.int16)
读取完数据之后,对数据进行处理之前,需要对数据进行格式转换,因为sampwidth = 2,
所以数据的宽度是两个字节,即为int16。
显示音频图像
时域
#Import matplotlib.pyplot as plt
time = np.arange(0,nframes)*(1.0 / framerate)
plt.plot(time, waveData) #设置横纵坐标数据
plt.xlabel(“Time(s)”)
plt.ylabel(“Amplitude”) #设置横纵坐标数据名称
plt.tittle(“single channel wavedate”) #设置表格名称
plt.grid(“on”) #设置显示标尺
语音采集
pa=PyAudio()
stream=pa.open(format = paInt16,channels=1,
rate=framerate,input=True,
frames_per_buffer=NUM_SAMPLES)
wav_data=[]
count=0
while count<TIME*20:#控制录音时间
string_audio_data = stream.read(NUM_SAMPLES)#一次性录音采样字节大小
wav_data.append(string_audio_data)
count+=1
print('.')
save_wave_file('01.wav',wav_data)
stream.close()
音频播放
def wavplay(filename):
CHUNK = 1024
f = wave.open(filename, "rb")
p = pyaudio.PyAudio()
stream = p.open(format = p.get_format_from_width(f.getsampwidth()),
channels = f.getnchannels(),
rate = f.getframerate(),
output = True)
i = 0;
while i * CHUNK < f.getnframes():
data = f.readframes(CHUNK)
stream.write(data)
i = i+1
stream.stop_stream()
stream.close()
p.terminate()