1

我正在尝试编写一个 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")
4

1 回答 1

0

尝试在此旁边使用“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')
于 2020-12-31T09:15:02.847 回答