改善语音识别,python

时间:2020-10-13 11:26:07

标签: python speech-recognition

我的代码可以正常工作,但是我想提高性能。

问题

  1. 有时会有延迟,代码被卡住,用户需要等待很长时间才能得到响应。
  2. 有时代码无法识别语音, 可以正确识别语音,但是什么也没发生。

我的代码:

import speech_recognition as sr
import keyboard
import os
import time


def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone(device_index=2) as source:
        print("Listening...")
        r.pause_threshold = 1
        try:
            audio = r.listen(source, timeout=2)
        except sr.WaitTimeoutError as e:
            return "None"
    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language='en-in')
        print(f"User said: {query}\n")

    except Exception as e:
        print(e)
        print("Unable to Recognizing your voice.")
        return "None"

    return query


if __name__ == '__main__':
    clear = lambda: os.system('cls')
    clear()
    while True:
      query = takeCommand().lower()
      # Do something with query

我有什么可以改善的吗?

2 个答案:

答案 0 :(得分:0)

您应该检查麦克风,因为音频信号可能存在​​问题,或者您可以尝试其他替代方法,例如apiai,wit,google-cloud-speech和Pocketsphinx。

您的代码看起来不错。

答案 1 :(得分:0)

尝试以下代码块。它经过了优化,仍然可以达到目的。您可以通过更改phrase_time_limit来设置收听时间。

def myCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        audio = r.listen(source, phrase_time_limit = 5)  
    try:
        command = r.recognize_google(audio).lower()
        print("you said: " + command)
        
    except sr.UnknownValueError:
        print("Sorry, Cant understand, Please say again")
        command = myCommand()
    return command