一、用apt-get安装
pyaudio是python的模块,在树莓派下安装pyaudio 首先需安装portaudio.dev
sudo apt-get install portaudio.dev
然后再:
sudo apt-get install python-pyaudio
如果的python3也可以是:
sudo apt-get install python3-pyaudio
注意:在导入pyaudio模块时只导入pyaudio即可,前面的python或python3去除
二、用pip安装
在pip安装模块是有可能报无法操作文件的错误,可以在pip前加上sudo,例如:
sudo pip install wave
在安装pyaudio前先安装portaudio.dev
<span style="font-size:14px;">sudo apt-get install portaudio.dev</span>
然后:
<span style="font-size:14px;">sudo pip install pyaudio</span>
注意:安装时有可能报gcc交叉编译错误,所有在安装pyaudio前还需安装一个软件,具体是什么,我也忘了。哈哈
所以还是用第一种吧。如果谁知道可以告诉我
三、树莓派通过pyaudio录音实例
<span style="font-size:14px;">def record_audio():
CHUNK = 512
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "apt.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print "* Recording audio..."
frames = []
print (RATE / CHUNK * RECORD_SECONDS)
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print "* done"
stream.stop_stream()
stream.close()
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()
if __name__=="__main__":
record_audio()</span>
注意:树莓派的音频输入支持
{'defaultSampleRate': 44100.0, 'defaultLowOutputLatency': -1.0, 'defaultLowInputLatency': 0.011609977324263039, 'maxInputChannels': 1, 'structVersion': 2, 'hostApi': 0, 'index': 0, 'defaultHighOutputLatency': -1.0, 'maxOutputChannels': 0, 'name': 'USB PnP Sound Device: USB Audio (hw:0,0)', 'defaultHighInputLatency': 0.046439909297052155}1、 缓冲块CHUNK不能过大512就可以 ,如果是1024就会报错
2、声道CHANNELS为1,为2会报错