2017-03-09 30 views
0

我試圖用8Khz的USB麥克風錄製語音,並使用python使用我的rpi3。我使用了pyaudio,sounddevice和soundfile庫,但他們只讓我以44100Hz或48000Hz的頻率進行採樣。當我試圖在8KHz的採樣我得到了以下錯誤:在python上使用8khz採樣率覆盆子pi3

"PortAudioError: Error opening InputStream: Invalid sample rate".

在另一方面,當我用命令:

"arecord -D plughw:1,0 -f S16_LE -r 8000 -d 2 test.wav" 

在命令行一切都很好。

這是我使用的代碼:

import pyaudio 
import wave 

FORMAT = pyaudio.paInt16 




CHANNELS = 1 
RATE = 8000 
CHUNK = 4000 
RECORD_SECONDS = 5 
WAVE_OUTPUT_FILENAME = "test1.wav" 

audio = pyaudio.PyAudio() 
print audio.get_default_input_device_info() 


# start Recording 
stream = audio.open(format=FORMAT, channels=CHANNELS,rate=RATE, input=True,frames_per_buffer=CHUNK,input_device_index=1) 
print ("recording...") 
frames = [] 

for i in range(0, int(RATE/CHUNK * RECORD_SECONDS)): 
    data = stream.read(CHUNK) 
    frames.append(data) 
print ("finished recording") 


# stop Recording 
stream.stop_stream() 
stream.close() 
audio.terminate() 



waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb') 
waveFile.setnchannels(CHANNELS) 
waveFile.setsampwidth(audio.get_sample_size(FORMAT)) 
waveFile.setframerate(RATE) 
waveFile.writeframes(b''.join(frames)) 
waveFile.close() 

這是結果:

{'defaultSampleRate': 44100.0, 'defaultLowOutputLatency': -1.0, 'defaultLowInputLatency': 0.008684807256235827, 'maxInputChannels': 1L, 'structVersion': 2L, 'hostApi': 0L, 'index': 1L, 'defaultHighOutputLatency': -1.0, 'maxOutputChannels': 0L, 'name': u'USB PnP Sound Device: Audio (hw:1,0)', 'defaultHighInputLatency': 0.034829931972789115} 

Traceback (most recent call last): 
    File "/home/pi/wave1.py", line 20, in <module> 
    stream = audio.open(format=FORMAT, channels=CHANNELS,rate=RATE, input=True,frames_per_buffer=CHUNK,input_device_index=1) 
    File "build/bdist.linux-armv7l/egg/pyaudio.py", line 750, in open 
    stream = Stream(self, *args, **kwargs) 
    File "build/bdist.linux-armv7l/egg/pyaudio.py", line 441, in __init__ 
    self._stream = pa.open(**arguments) 
IOError: [Errno -9997] Invalid sample rate 

我檢查,我知道,我使用的是正確的設備,但你可以看到默認採樣率沒有變化,我仍然得到相同的錯誤。

+0

那麼你的問題是什麼? – feedMe

+0

如何使用python以8KHz採樣? – tomash

+0

你可以顯示你用來記錄音頻的Python代碼嗎? –

回答

0

您可能會在Python腳本中打開錯誤的設備。可用的採樣率取決於您的硬件,並且在PyAudio中打開的採樣率不支持8kHz,而您使用arecord打開的採樣率顯然確實如此。在Linux下可用的不同API似乎以不同的方式對硬件進行索引,並且可能非常令人困惑(我當然發現它)。

在我的皮,將USB麥克風是設備2,和我在44.1kHz的採樣,所以我有:

import pyaudio 

DEVICE = 2 #USB Audio Device 
CHANNELS = 1 
FRAME_RATE = 44100 
FORMAT = pyaudio.paInt16 

def init_stream(): 
    stream = p.open(format = FORMAT, 
        channels = CHANNELS, 
        rate = FRAME_RATE, 
        input = True, 
        output = False, 
        input_device_index = DEVICE, 
        frames_per_buffer = 8192, 
        stream_callback = callback) 
    return (stream) 

要獲取音頻設備的列表,通過PyAudio作爲索引(等選擇正確的設備),您可以使用this的答案中的代碼。