Мем-микрофон Adafruit I2S не работает с распознаванием речи Contune. (API Google Cloud Speech)

Я использую эту библиотеку с Raspberry pi 3 с Mems-микрофоном Raspbian и Adafruit I2S. Я могу работать с микрофоном i2s с raspberry pi, и он отлично работает для нормальной записи, но при использовании Speech_Recognition с Google Speech Cloud API он не работал, поэтому я проделал некоторые хитрости, и он отлично работает с microphone_recognition.py.

Уловка, которую я использовал, заключается в

микрофон_recognition.py

r = sr.Recognizer()
with sr.Microphone(device_index = 2, sample_rate = 48000) as source:
    print("Say something!")
    audio = r.record(source, duration = 5)

распознавание_ речи / __ init__.py

self.device_index = device_index
            self.format = self.pyaudio_module.paInt32

и он отлично работал на выходе

ALSA lib pcm.c: 2495: (snd_pcm_open_noupdate) Неизвестный вызов PCM bluealsa connect (2) в / tmp / jack-1000 / default / jack_0 завершился неудачно (err = Нет такого файла или каталога) попытка подключения к серверу не удалась Скажите что-нибудь! Google Cloud Speech думает, что вы передали привет

Но при попытке background_listening.py

import time

import speech_recognition as sr

# this is called from the background thread

def callback(recognizer, audio):

    GOOGLE_KEY= r"""{ MY KEY }"""

    # received audio data, now we'll recognize it using Google Speech Recognition
    try:
        print("Google Speech Recognition thinks you said " + recognizer.recognize_google_cloud(audio, credentials_json=GOOGLE_KEY))
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
    except sr.RequestError as e:
        print("Could not request results from Google Speech Recognition service; {0}".format(e))


r = sr.Recognizer() 
with sr.Microphone(device_index=2, sample_rate = 48000) as source:
    r.adjust_for_ambient_noise(source)  # we only need to calibrate once, before we start listening

# start listening in the background (note that we don't have to do this inside a `with` statement)
stop_listening = r.listen_in_background(source, callback)
# `stop_listening` is now a function that, when called, stops background listening

# do some unrelated computations for 5 seconds
for _ in range(50): time.sleep(0.1)  # we're still listening even though the main thread is doing other things

# calling this function requests that the background listener stop listening
stop_listening(wait_for_stop=False)

# do some more unrelated things
while True: time.sleep(0.1) 

ALSA lib pcm.c: 2495: (snd_pcm_open_noupdate) Неизвестный PCM bluealsa connect (2) вызов / tmp / jack-1000 / default / jack_0 завершился неудачно (err = Нет такого файла или каталога) попытка подключения к серверу не удалась

Я использую те же настройки Speech_recognition / init. Не дает выхода.

Дополнение к вопросу после отладки

Я остаюсь в приведенном ниже цикле, не продвигаюсь вперед и не могу вызвать обратный вызов (распознаватель, аудио). Я использую ### init.py self.format = self.pyaudio_module.paInt32 и код любви тоже из того же.

Некоторая отладка -

                print(format(energy)) 
        print(format(self.energy_threshold))
                if energy > self.energy_threshold:
        print("inside energy") 
        print(format(energy)) 
            print(format(self.energy_threshold)) 
        break

                # dynamically adjust the energy threshold using asymmetric weighted average
                if self.dynamic_energy_threshold:
        print(" inside dynamic_energy_threshold")
                    damping = self.dynamic_energy_adjustment_damping ** seconds_per_buffer 
                    target_energy = energy * self.dynamic_energy_ratio
                    self.energy_threshold = self.energy_threshold * damping + target_energy * (1 - damping)
        print(format(self.energy_threshold))
        print("end dynamic_energy_threshold") 

102982050 117976102.818 - Начать и всегда на высоком уровне, чтобы никогда не уходить, разорвать этот цикл, Даже после разговора, внутри dynamic_energy_threshold 119548935.608 end dynamic_energy_threshold внутри listen -6.1.1 97861662 119548935.608 внутри dynamic_energy_threshold.5120722993.56 endthreshold7406_energy_energy_269

Здесь я попытался уравнять энергию и энергию тришолда и разорвать петлю.

            print(format(energy)) 
    print(format(self.energy_threshold))
    **self.energy_threshold = float(energy)**
            if energy >= self.energy_threshold:
    **print("inside energy")** 
    print(format(energy)) 
        print(format(self.energy_threshold)) 
    break

Выход

105836705 116487614.952 = Это всегда высокий порог энергии. и продолжаем цикл внутри энергии 105836705 105836705.0


person Hitesh Patil    schedule 21.06.2018    source источник


Ответы (1)


Итак, я обошелся, Soltion - Speech_recognition / __ init__.py - Lib

Microphone .__ init __ () - Метод

self.format = self.pyaudio_module.paInt32

Распознаватель / adjust_for_ambient_noise - Метод

energy = audioop.rms(buffer, source.SAMPLE_WIDTH)/1000000 

И он работает действительно идеально, но теперь мне нужно найти способ остановить отправку запроса в Google Speech API, если нет речи.

person Hitesh Patil    schedule 23.06.2018