Skip to main content
 首页 » 编程设计

python之说了Python怎么开始录音

2025年05月04日22kuangbin

我正在尝试制作一个使用语音识别的程序。现在我遇到了一个问题,这是你必须按下按钮或 Enter 才能开始语音识别。在 Python 3 中,有没有一种方法可以让您说出一个短语(有点像 Hey Google),它开始识别语音?
这是我的代码:

录制音频代码:

r = sr.Recognizer() 
 
with sr.Microphone() as source: 
    audio = r.listen(source) 
x = r.recognize_google(audio) 
 
print("I'm listening!") 
 
try: 
    print("You said: " + r.recognize_google(audio)) 
except speech_recognition.UnknownValueError: 
    print("I am sorry but I couldn't understand you, try again.") 
except speech_recognition.RequestError as e: 
    print("Could not request results from Google Speech Recognition service; {0}".format(e)) 

提前致谢!

请您参考如下方法:

是的,基本上您必须将识别分为两部分:关键字识别(只听关键字)和主要识别(识别用户在关键字后说的话)。请注意,这意味着您的程序将始终处于监听状态。

对于关键字识别,您可以使用Recognizer() 的listen_in_background 方法并在您提供的任何回调中扫描关键字。如果找到关键字,则调用 Recognizer().listen(source)。

由于收听关键字需要您的程序不断收听和识别,因此您不想使用任何需要互联网连接的语音识别 API(Bing、Google、Watson、Houndify 等...)。这是因为所有这些都有每月的 API 限制,您很容易就会用完这些限制。您想保存这些 API 以供实际识别。我相信您唯一的离线选择是使用 recognize_sphinx 或 snowboy 热词检测。我从来没有真正使用过 Snowboy(尽管我听说它非常好),因为它在 Windows 上不起作用(或者至少在我编写程序时它不起作用),但是 Sphinx 有一个关键字检测工具。

基本上,您传递 sphinx_recognizer 关键字以及它应该通过元组拾取这些关键字的敏感度,它会尝试专注于在语音中查找这些词。请注意,关键字越敏感,误报就越多。

这是一个例子:

import speech_recognition as sr 
import time 
 
r = sr.Recognizer() 
 
# Words that sphinx should listen closely for. 0-1 is the sensitivity 
# of the wake word. 
keywords = [("google", 1), ("hey google", 1), ] 
 
source = sr.Microphone() 
 
 
def callback(recognizer, audio):  # this is called from the background thread 
 
    try: 
        speech_as_text = recognizer.recognize_sphinx(audio, keyword_entries=keywords) 
        print(speech_as_text) 
 
        # Look for your "Ok Google" keyword in speech_as_text 
        if "google" in speech_as_text or "hey google": 
            recognize_main() 
 
    except sr.UnknownValueError: 
        print("Oops! Didn't catch that") 
 
 
def recognize_main(): 
    print("Recognizing Main...") 
    audio_data = r.listen(source) 
    # interpret the user's words however you normally interpret them 
 
 
def start_recognizer(): 
    r.listen_in_background(source, callback) 
    time.sleep(1000000) 
 
 
start_recognizer() 

此链接在使用 speech_recognition 库时非常有用:

https://github.com/Uberi/speech_recognition/blob/master/reference/library-reference.rst