回顾教程编写之初,是为了看懂目前许多开源应用,比如目前百度dueros,或是国内respeaker等语音开源项目都是基于python编写。那么今天进入正题,如何用python录音以及播放wav格式音频。
查找声卡:
root@ubuntu:/mnt# cat NetRouterPythonVoce/getinfo.py
import pyaudio
p = pyaudio.PyAudio()
for i in range(p.get_device_count()):
dev = p.get_device_info_by_index(i)
print((i,dev[‘name’],dev[‘maxInputChannels’]))
录音:
root@ubuntu:/mnt# cat NetRouterRecord.py
#coding=utf-8
from pyaudio import PyAudio,paInt16
from datetime import datetime
import wave
#define of params
NUM_SAMPLES = 2000
framerate = 16000
channels = 1
sampwidth = 2
#record time
TIME = 10
def save_wave_file(filename, data):
‘’‘save the date to the wav file’’’
wf = wave.open(filename, ‘wb’)
wf.setnchannels(channels)
wf.setsampwidth(sampwidth)
wf.setframerate(framerate)
wf.writeframes("".join(data))
wf.close()
def record_wave():
#open the input of wave
pa = PyAudio()
stream = pa.open(format = paInt16, channels = 1,
rate = framerate, input = True,
frames_per_buffer = NUM_SAMPLES)
save_buffer = []
count = 0
while count < TIME*4:
#read NUM_SAMPLES sampling data
string_audio_data = stream.read(NUM_SAMPLES)
save_buffer.append(string_audio_data)
count += 1
print ‘.’
filename = datetime.now().strftime("%Y-%m-%d_%H_%M_%S")+".wav"
save_wave_file(filename, save_buffer)
save_buffer = []
print filename, "saved"
def main():
record_wave()
if name == “main”:
main()
播放:
root@ubuntu:/mnt# cat NetRouterPythonVoce/play_wav.py
“”“PyAudio Example: Play a WAVE file.”""
import pyaudio
import wave
import sys
CHUNK = 1024
if len(sys.argv) < 2:
print(“Plays a wave file.\n\nUsage: %s filename.wav” % sys.argv[0])
sys.exit(-1)
wf = wave.open(sys.argv[1], ‘rb’)
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True)
data = wf.readframes(CHUNK)
while data != ‘’:
stream.write(data)
data = wf.readframes(CHUNK)
stream.stop_stream()
stream.close()
p.terminate()
- 列表