1

I am trying to write a gTTS python program that converts text to speech and accepts commands that it is told, but when I run the code, I get no response at all, no errors in the terminal and no sound is played, I am not sure what to do and I am not seeing any errors in my program. I am using Sublime Text on MacOS. Please help!!

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")
ZiaCassim
  • 21
  • 1

1 Answers1

0

Try using the "pttsx3" library along side this. Here is some sample code. This should take in commands and then respond back to you.

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')
AKD
  • 68
  • 10