说了Python如何开始录音?

How to start recording when something is said Python?

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

录制音频代码:

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()

这个 link 在使用 speech_recognition 库时非常有用:

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

代码:

from pocketsphinx import LiveSpeech
import os
for i in LiveSpeech():
    print(i)
    if "hey Google" in str(i):
       os.startfile("Your File.your_format")
#works Perfectly and if you want to hide python console then save as youfile.pyw