I have a STT combined with a TTS program that runs on a raspberry pi. I was able to put a command that says "error" when the recognizer fails to detect a word. We assigned words as command to save mp3 files and then play them. How do I add an additional "error" command when our recognizer successfully read a word that is not in our commands? My program looks like these.
import RPi.GPIO as GPIO
import time
import sys
import speech_recognition as sr
import pyttsx3
from gtts import gTTS
import os
import playsound
from pygame import mixer
import traceback
GPIO.setmode(GPIO.BCM)
GPIO.setup(2 ,GPIO.IN)
prev_input = 1
mixer.init()
listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty("voices")
rate = engine.getProperty("rate")
engine.setProperty("rate", 180)
def talk(text):
engine.say(text)
engine.runAndWait()
while True:
input = GPIO.input(2)
if ((not prev_input) and input):
try:
with sr.Microphone() as source:
print('You can speak now')
talk("You can speak now")
listener.phrase_threshold = 2
audio = listener.listen(source, 8)
command = listener.recognize_google(audio)
text = command
speech = gTTS(text=text, lang="en", slow=False, )
speech.save("texttospeech.mp3")
print(command)
if command == command:
if command == "hello":
print("good morning")
tts = gTTS(text="good morning", lang="en")
filename="goodmorning.mp3"
tts.save("goodmorning.mp3")
mixer.music.load("goodmorning.mp3")
mixer.music.play()
if command == "hey":
print("hi there")
tts = gTTS(text="hi there", lang="en")
filename="hithere.mp3"
tts.save("hithere.mp3")
mixer.music.load("hithere.mp3")
mixer.music.play()
if command == "yes":
print("no")
tts = gTTS(text="no", lang="en")
filename="no.mp3"
tts.save("no.mp3")
mixer.music.load("no.mp3")
mixer.music.play()
except Exception:
traceback.print_exc()
tts = gTTS(text="error", lang="en")
filename = "error.mp3"
tts.save("error.mp3")
mixer.music.load("error.mp3")
mixer.music.play()
prev_input = input
time.sleep(.05)`
As you can see, there are only 3 commands in the program, I want all other readings to prompt an "error" command similar to the command in my except block. I have tried using elif on all the commands but it continuously played the error mp3 file.
Use if elif else