2014-02-21 30 views
1

我試圖設置一個持久音頻監聽器。這個想法是記錄一些音頻,發送到Google的語音識別API,然後根據所說的內容運行命令。我知道這已經實施了幾次;其實,我在這裏借用的代碼量好(稍微適應):python音頻監聽器在幾分鐘後失去質量

https://github.com/jeysonmc/python-google-speech-scripts/blob/master/stt_google.py

我希望它在後臺運行一致。現在,它在最初的幾分鐘內效果很好,但過了一段時間後,錄音機需要更長的時間才能停止錄音(即使完全靜音),但我不確定是否將正確的音頻發送給Google,因爲識別的質量急劇下降。請注意,我目前正在使用非常積極的嘗試/除非繞過錄制第一個音頻後出現的IOErrors。任何更優雅和/或有效的解決方案當然都是受歡迎的。我的代碼如下:

#config 
chunk = 1024 
FORMAT = pyaudio.paInt16 
CHANNELS = 1 
RATE = 48000 
THRESHOLD = 180 #The threshold intensity that defines silence signal (lower than). 
SILENCE_LIMIT = 2 #Silence limit in seconds. The max ammount of seconds where only silence is recorded. When this time passes the recording finishes and the file is delivered. 

p = pyaudio.PyAudio() 

print "* listening. CTRL+C to finish." 

all_m = [] 
data = '' 
rel = RATE/chunk 
slid_win = deque(maxlen=SILENCE_LIMIT*rel) 
started = False 

while (True): 
    try: 
     #listening loop, open new stream each time 
     stream = p.open(format = FORMAT,channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = chunk) 
     data = stream.read(chunk) 

     slid_win.append (abs(audioop.avg(data, 2))) 

     #detect noise 
     if(True in [ x>THRESHOLD for x in slid_win]): 
      if(not started): 
       print "starting record" 
      started = True 
      all_m.append(data) 
     elif (started==True): 
      stream.close() 
      print "finished" 

      #the limit was reached, finish capture and deliver 
      filename = save_speech(all_m,p) 
      google(filename) 

      #reset all 
      started = False 
      slid_win = deque(maxlen=SILENCE_LIMIT*rel) 
      all_m= [] 

      print "listening ..." 
    except IOError as e: 
     print "Caught IOError" 
     stream.close() 
     pass 

其餘代碼只涉及轉換爲flac和向Google發送請求。

重申一下,我的代碼在開始的幾分鐘內運行良好,前提是沒有太多的背景噪音,並且直接向麥克風說出命令。我已經試過在任何文件被保存/發送給Google之前關閉PyAudio流,除了在流打開的位置移動(最初在while()循環之外)。這兩個改變似乎都有所幫助。然而,由於隨着時間的推移,錄音指標變得越來越不準確,我的預感是它與滑動窗口的「錯位」有關。可以肯定是錯的。

在此先感謝您的幫助。

回答

0

更有效的方法是使用Pocketsphinx專門設計用於連續收聽的關鍵字識別模式。要嘗試它,你需要從幹線和運行上的文件察覺籤最新開發版:

 pocketsphinx_continuouos -kws "oh mighty computer" -infile file.wav 

將沒有互聯網連接的需要,去除噪聲,您將能夠調整檢測閾值和關鍵字發音。

您可以通過Python的API使用pocketspinx:

config = Decoder.default_config() 
config.set_string('-kws', "oh mighty computer") 
decoder = Decoder(config) 

decoder.start_utt('') 
stream = open(path.join('file.wav'), 'rb') 
while True: 
    buf = stream.read(1024) 
    decoder.process_raw(buf, False, False) 
+0

感謝 - 這肯定是有幫助的,我給它一個鏡頭。實際上,我原本計劃使用Pocketsphinx,但由於最終的部署將在Raspberry Pi上進行,因此上面的實現看起來就像安裝/安裝一樣簡單。你對如何優化我的原始代碼有任何想法嗎? – user3335825

+0

不,沒有想法。流媒體音頻到谷歌是由設計打破。 –