【问题标题】:Make delay of answer shorter缩短回答延迟时间
【发布时间】:2020-10-21 00:15:38
【问题描述】:

我正在 python 上制作语音助手。
代码如下:

import os
import time
import playsound
import speech_recognition as sr
from gtts import gTTS


def speak(text):
    tts = gTTS(text=text, lang="en")
    filename = "voice.mp3"
    tts.save(filename)
    playsound.playsound(filename)


def get_audio():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        audio = r.listen(source)
        said = ""

        try:
            said = r.recognize_google(audio)
            print(said)
        except Exception as e:
            print("Exception: " + str(e))

    return said

text = get_audio()

if "hello" in text:
    speak("Hi, how are you?")

当我说“你好”时,它会思考 2 秒钟,然后说“嗨,你好吗?”
也许是因为我正在保存 mp3 文件?如何让程序无延迟应答?

【问题讨论】:

  • 您是否尝试识别以前录制的文件以查看需要多长时间?您是否尝试过计算捕获所需的时间并与识别的总体时间进行比较?使用 time.perf_counter docs.python.org/3/library/time.html
  • 只是'time.perf_counter()'?没有'time.perf_counter(2)'?
  • 不确定 2 的用途。像在第一个 starttime = time.perf_counter() 中一样使用它,然后是你想要计时的代码,然后是 elapsed=starttime-time.perf_counter() 并使用 elapsed...
  • 糟糕,我的意思是elapsed=time.perf_counter()-starttime
  • 哇!有用!快一点)谢谢!

标签: python voice-recognition voice assistant gtts


【解决方案1】:
import os
import time
import playsound
import speech_recognition as sr
from gtts import gTTS

starttime = time.perf_counter()

def speak(text):
    tts = gTTS(text=text, lang="en")
    filename = "voice.mp3"
    tts.save(filename)
    playsound.playsound(filename)

elapsed=time.perf_counter()-starttime    

def get_audio():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        audio = r.listen(source)
        said = ""

        try:
            said = r.recognize_google(audio)
            print(said)
        except Exception as e:
            print("Exception: " + str(e))

    return said

text = get_audio()

if "hello" in text:
    speak("Hi, how are you?")

【讨论】:

    猜你喜欢
    • 2014-01-04
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    相关资源
    最近更新 更多