按键时停止语音识别 [英] Stop speech recognition on keypress

查看:13
本文介绍了按键时停止语音识别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以停止在按键盘时收听音频吗? 我尝试这样更改记录函数(在init.py中):

    def record(self, source, duration=None, offset=None):
        """
        Records up to ``duration`` seconds of audio from ``source`` (an ``AudioSource`` instance) starting at ``offset`` (or at the beginning if not specified) into an ``AudioData`` instance, which it returns.

        If ``duration`` is not specified, then it will record until there is no more audio input.
        """
        assert isinstance(source, AudioSource), "Source must be an audio source"
        assert source.stream is not None, "Audio source must be entered before recording, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?"

        frames = io.BytesIO()
        seconds_per_buffer = (source.CHUNK + 0.0) / source.SAMPLE_RATE
        elapsed_time = 0
        offset_time = 0
        offset_reached = False
        while True:  # loop for the total number of chunks needed
            if offset and not offset_reached:
                offset_time += seconds_per_buffer
                if offset_time > offset:
                    offset_reached = True

            buffer = source.stream.read(source.CHUNK)
            if len(buffer) == 0: break

            if offset_reached or not offset:
                elapsed_time += seconds_per_buffer
                if keyboard.read_key() == "p":
                    print("
You pressed p")
                    break

                frames.write(buffer)

        frame_data = frames.getvalue()
        frames.close()
        return AudioData(frame_data, source.SAMPLE_RATE, source.SAMPLE_WIDTH)

在我的主脚本中调用它,如下所示:

def Main():
r = sr.Recognizer()
try:
    with sr.Microphone() as source:
        print("Listening....")
        audio = r.record(source)
        print("Recognizing....")
        r.adjust_for_ambient_noise(source)
    text = r.recognize_google(audio)
    print(text.lower())
    if "lock computer" in text.lower():
        ctypes.windll.user32.LockWorkStation()
    elif "joke" in text.lower():
        joke = pyjokes.get_joke()
        speak(joke)
except Exception as e:
    print(e)
    Main()

这会收听音频,并在我按p但无法识别时停止收听

推荐答案

我弄清楚了,我保存了输入文件,发现里面没有音频,所以谷歌无法识别它。 错误在此块中:

                if keyboard.read_key() == "p":
                    print("
You pressed p")
                    break

我将其更改为:

                if keyboard.read_key() == "p":
                    print("
You pressed p")
                    pressed = True
                    break
并复制LISTEN函数并对其进行复制,将其名称更改为Listen1 现在,当我按下P键时,它停止收听,识别也在工作。 像魅力😍一样工作。

这篇关于按键时停止语音识别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆