import wave import pyaudio
# 定義數(shù)據(jù)流塊 CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 2 RATE = 44100 # 錄音時間 RECORD_SECONDS = 5 # 要寫入的文件名 WAVE_OUTPUT_FILENAME = 'output.wav' # 創(chuàng)建PyAudio對象 p = pyaudio.PyAudio()
# 打開數(shù)據(jù)流 stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)
print('* recording')
# 開始錄音 frames = [] for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)): data = stream.read(CHUNK) frames.append(data)
print('* done recording')
# 停止數(shù)據(jù)流 stream.stop_stream() stream.close()
# 關(guān)閉PyAudio p.terminate()
# 寫入錄音文件 wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb') wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(FORMAT)) wf.setframerate(RATE) wf.writeframes(b''.join(frames)) wf.close()
import wave import numpy from pyaudio import PyAudio import matplotlib.pyplot as plt
# 只讀方式打開WAV文件 wf = wave.open('./output.wav', 'rb') # 創(chuàng)建PyAudio對象 p = PyAudio() stream = p.open(format = p.get_format_from_width(wf.getsampwidth()), channels = wf.getnchannels(), rate = wf.getframerate(), output = True) nframes = wf.getnframes() framerate = wf.getframerate()
# 讀取完整的幀數(shù)據(jù)到str_data中,這是一個string類型的數(shù)據(jù) str_data = wf.readframes(nframes) wf.close()
# 將波形數(shù)據(jù)轉(zhuǎn)換成數(shù)組 wave_data = numpy.fromstring(str_data, dtype=numpy.short) # 將wave_data數(shù)組改為2列,行數(shù)自動匹配 wave_data.shape = -1,2 # 將數(shù)組轉(zhuǎn)置 wave_data = wave_data.T
def time_plt(): # time也是一個數(shù)組,與wave_data[0]或wave_data[1]配對形成系列點坐標(biāo) time = numpy.arange(0, nframes)*(1.0/framerate) # 繪制波形圖 plt.subplot(211) plt.plot(time, wave_data[0], c='r') plt.subplot(212) plt.plot(time, wave_data[1], c='g') plt.xlabel('time (seconds)') plt.show()
def freq(): # 采樣點數(shù),修改采樣點數(shù)和起始位置進(jìn)行不同位置和長度的音頻波形分析 N = 44100 start = 0 # 開始采樣位置 df = framerate/(N-1) # 分辨率 freq = [df*n for n in range(0, N)] # N個元素 wave_data2 = wave_data[0][start:start+N] c = numpy.fft.fft(wave_data2)*2/N # 常規(guī)顯示采樣頻率一半的頻譜 d = int(len(c)/2) # 僅顯示頻率在4000以下的頻譜 while freq[d] > 4000: d -= 10 plt.plot(freq[:d-1], abs(c[:d-1]), 'r') plt.show()
def main(): time_plt() freq()
if __name__ == '__main__': main()
|