gTTS 程序无响应

问题描述

我正在尝试编写一个 gTTS python 程序,将文本转换为语音并接受它被告知的命令,但是当我运行代码时,我根本没有得到任何响应,终端中没有错误,也没有播放声音,我不知道该怎么做,也没有在我的程序中看到任何错误。我在 MacOS 上使用 Sublime Text。请帮忙!!

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


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("hello,how are you?")

if "What is your name" in text:
    speak("My name is John")

解决方法

尝试同时使用“pttsx3”库。 这是一些示例代码。这应该接收命令,然后回复您。

import pyttsx3
import speech_recognition as sr
import wikipedia

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice',voices[0].id)



def speak(audio):
    engine.say(audio)
    engine.runAndWait()

def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)

    try:
        print("Recognizing...")
        query = r.recognize_google(audio,language = 'en-in')
        print(f"User said: {query}\n")

    except:
        print("Say that again please...")
        return "None"
    return query

if __name__ == "__main__":
    while True:
        query = takeCommand().lower()

        # code for executing tasks based on the query or input
        if 'wikipedia' in query:
            speak("Searching Wikipedia...")
            query = query.replace("wikipedia","")
            results = wikipedia.summary(query,sentences = 3)
            speak("According to Wikipedia")
            print(results)
            speak(results)
        if 'hi' in query:
            speak('hello')

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...