pyttsx engine.say is delayed - python

import os
import speech_recognition as sr
import pyttsx3
engine = pyttsx3.init()
def firstMain():
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
user = r.recognize_google(audio).lower()
print(user)
if "hey windows" in user: # 2
engine.say("Hi, want me to open something?")
def secondMain():
r2 = sr.Recognizer()
with sr.Microphone() as source2:
audio2 = r2.listen(source2)
user2 = r2.recognize_google(audio2).lower()
print(user2)
if "google" in user2 or "chrome" in user2:
os.system("start chrome.exe") # 1
firstMain()
secondMain()
engine.runAndWait()
The problem is that the engine.say command is executed/heard when the bottom if condition (Look #1) is executed when it should be executed/heard in the top if condition (Look # 2)

Related

How to set pyttsx3 voice to male

When I use pyttsx3 to speak only female voice how can I change it to male
rate and frequency doesn't work. please update this code -
import speech_recognition as sr
import pyttsx3
listener = sr.Recognizer()
engine = pyttsx3.init()
engine.say('Hello, I am assistant vocal personnel virtuel')
engine.say('what can i help you with')
engine.runAndWait()
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'hey vocal' in command:
print(command)
except:
pass
I am building a voice assistant.
This small demo should help you.
It will speak all available names while function change_voice will give you control over the rate and volume of each voice.
import pyttsx3
engine = pyttsx3.init()
# return a list of all voices
voices = engine.getProperty('voices')
engine.runAndWait()
def change_voice(indx, rate = 120, volume = 0.5):
idname = voices[ indx ].id
engine.setProperty('voice', idname)
engine.setProperty('rate', rate)
engine.setProperty('volume', volume)
engine.runAndWait()
print(f"Found {len(voices)} voices")
# enunciate all available names
for indx, v in enumerate(voices):
change_voice(indx, rate = 140, volume = 1)
print(f"I am {v.name}")
engine.say(f"I am {v.name}")
engine.runAndWait()

How to use responses in neuralintents python library

I created a voice assistant using python neuralintents module. but it didn't give a way to use responses in intents.json to give a feedback for user. Instead it is mapping response to a function.
Is there any way to use responses in intents.json.
I got this by watching this tutorial :
https://youtu.be/SXsyLdKkKX0
Github repo :
https://github.com/NeuralNine/neuralintents
Source code from video
from email.mime import audio
from fileinput import filename
from neuralintents import GenericAssistant
import speech_recognition
import pyttsx3 as tts
import sys
import webbrowser
recognizer = speech_recognition.Recognizer()
speaker = tts.init()
speaker.setProperty('rate', 150)
todo_list = ['Go shopping', 'Clean Room', 'Recpard Videos']
def create_note():
global recognizer
speaker.say("What do you want to write into your note")
speaker.runAndWait()
done = False
while not done:
try:
with speech_recognition.Microphone as mic:
recognizer.adjust_for_ambient_noise(mic, duration=0.2)
audio = recognizer.listen(mic)
note = recognizer.recognize_google(audio)
note = note.lower()
speaker.say("Choose a filename!")
speaker.runAndWait()
recognizer.adjust_for_ambient_noise(mic, duration=0.2)
audio = recognizer.listen(mic)
filename = recognizer.recognize_google(audio)
filename = filename.lower()
with open(filename, 'w') as f:
f.write(note)
done = True
speaker.say(f"I sucessfully created the note {filename}")
speaker.runAndWait
except speech_recognition.UnknownValueError:
recognizer = speech_recognition.Recognizer()
speaker.say("I did not understand you! Please try again!")
speaker.runAndWait()
def add_todo():
global recognizer
speaker.say("What doto do you want to add?")
speaker.runAndWait()
done = False
while not done:
try:
with speech_recognition.Microphone() as mic:
recognizer.adjust_for_ambient_noise(mic, duration=0.2)
audio = recognizer.listen(mic)
item = recognizer.recognize_google(audio)
item = item.lower()
todo_list.append(item)
done = True
speaker.say(f"I added {item} to the to do list!")
speaker.runAndWait()
except speech_recognition.UnknownValueError:
recognizer = speech_recognition.Recognizer()
speaker.say("I did not understand. Please try again!")
speaker.runAndWait()
def show_todos():
speaker.say("The items in your to do list are following")
for item in todo_list:
speaker.say(item)
speaker.runAndWait()
def hello():
speaker.say("Hello. What can I do for you?")
speaker.runAndWait()
def exitt():
speaker.say("Bye")
speaker.runAndWait()
sys.exit(0)
mapppings = {
"greeting": hello,
"create_note": create_note,
"add_todos": add_todo,
"show_todos": show_todos,
"goodbye": exitt,
}
assistant = GenericAssistant('intents.json', intent_methods=mapppings)
assistant.train_model()
assistant.save_model()
def talk(text):
engine = tts.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
engine. setProperty("rate", 150)
engine.say(text)
engine.runAndWait()
while True:
try:
with speech_recognition.Microphone() as mic:
recognizer.adjust_for_ambient_noise(mic, duration=0.2)
audio = recognizer.listen(mic)
command = recognizer.recognize_google(audio)
command = command.lower()
assistant.request(command)
except speech_recognition.UnknownValueError:
recognizer = speech_recognition.Recognizer()
if you want the assistant to speak the response you call the function talk and pass assistant.request(command) as parameter, but if you have bindings for adding todo ect. u first call the assistant.request(command) alone and after that you chec if the request has any response and if it does you pass the response to the talk function
def talk(text):
engine = tts.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
engine. setProperty("rate", 150)
engine.say(text)
engine.runAndWait()
while True:
try:
with speech_recognition.Microphone() as mic:
recognizer.adjust_for_ambient_noise(mic, duration=0.2)
audio = recognizer.listen(mic)
command = recognizer.recognize_google(audio)
command = command.lower()
assistant.request(command)
if(assistant.request(command))
talk(assistant.request(command))
except speech_recognition.UnknownValueError:
recognizer = speech_recognition.Recognizer()

engine.runandWait() get stuck

My script just stop and get stuck after engine.runandWait()... If someone has any idea of how to make it continue I would appreciate !
It seems that the answer isn't in the script itself because I tried scripts that are super simple... I also tried to uninstall and reinstall portaudio, pyaudio and pyttsx3
Here is my script :
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import time
import pyjokes
listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.setProperty('voices', "french")
def talk(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
def take_command():
command = ''
try:
with sr.Microphone() as source:
print("...")
voice = listener.listen(source)
command = listener.recognize_google(voice,language = 'fr-FR')
command = command.lower()
except:
talk("Je me mets en veille")
pass
return command
def run_jeff(run):
command = take_command()
if 'youtube' in command:
command = command.replace('youtube','')
command = command.replace('ouvre','')
pywhatkit.playonyt(command)
elif "stop" in command:
talk("Je vais dodo")
run = False
elif 'bonjour' in command or 'salut' in command :
talk('Bonjour, comment allez-vous ?')
talk(info)
elif 'blague' in command :
talk(pyjokes.get_joke())
else :
talk("Pouvez-vous répétez je n'ai pas compris ?")
print(command)
run = True
while True:
run_jeff(run)
if run == False:
exit()
In the def talk section, you can remove the first line and in the while True statement, delete if run == False, and add a elif statement to the take command sections saying elif 'thank you' in command: exit(the name of your assistant). Try it
Here is a short pyttsx testing program.
Save it as 'pyttsx_test.py' then run it.
If your version is working correctly it will speak the code and print it to shell.
"""pyttsx_test.py
I am a text to speech test
"""
import pyttsx3
engine = pyttsx3.Engine()
engine.setProperty( "rate", 200 )
engine.setProperty( "volume", 1.0 )
engine.say( 'say something' )
engine.runAndWait()
with open( 'pyttsx_test.py', mode='rt') as files:
lines = files.readlines()
lines = [ x.strip(' ') for x in lines ] # remove un-necessary spaces
lines = [ x for x in lines if x!='\n'] # remove empty lines
for a in lines:
print( a, end ='' )
engine.say( a )
engine.runAndWait()
You should change your input device using device_index. (default=0)
with sr.Microphone(device_index=0) as source:
You can see all your devices using:
for index, name in enumerate(sr.Microphone.list_microphone_names()):
print(f'{index}, {name}')
Every time you initiate the engine or "init()" you have to set property again. You duplicated your lines and used it wrong.
if you wish it to work delete thoes lines -
engine = pyttsx3.init()
voices = engine.setProperty('voices', "french")
def talk(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
and replace them with this -
def talk(text):
engine = pyttsx3.init()
voices = engine.setProperty('voices', "french")
engine.say(text)
engine.runAndWait()

Create a Loop of SpeechRecognition

I am creating a voice assistant in python and I would like to know how I can make a loop so that every time the assistant responds, the microphone is activated so I can ask him again
#Use Google TTS for say something
def speak(text):
tts = gTTS(text=text, lang="es", slow=False)
filename = "voiceww.mp3"
tts.save(filename)
playsound.playsound(filename)
#Use mic for get my voice
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
print('Di algo')
r.adjust_for_ambient_noise(source, duration=1)
audio = r.listen(source)
said = ""
#Print the answer in console
try:
#print('Listo')
said = r.recognize_google(audio, language='es')
print(said)
except Exception as e:
print("Exception: " + str(e))
return said
#Here the function activates
text = get_audio()
#This is a example question
if 'hello computer' in text:
speak('Hi! How are you?')
#This is where I want to turn on the microphone again, process my voice and say the answer and so on to infinity
#Use Google TTS for say something
def speak(text):
tts = gTTS(text=text, lang="es", slow=False)
filename = "voiceww.mp3"
tts.save(filename)
playsound.playsound(filename)
#Use mic for get my voice
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
print('Di algo')
r.adjust_for_ambient_noise(source, duration=1)
audio = r.listen(source)
said = ""
#Print the answer in console
try:
#print('Listo')
said = r.recognize_google(audio, language='es')
print(said)
except Exception as e:
print("Exception: " + str(e))
return said
This is how you keep your microphone turned on:
while True:
# Here the function activates
text = get_audio().lower
# These are examples
if 'hello computer' in text:
speak('Hi! How are you?')
elif "good morning" in text:
speak("Hey good morning")

How to make chatbot starts listening on calling its name?

I want my python chatbot to start listening when I say "Echo". How do I do that? A snippet of chatbot is below.
import speech_recognition as sr
running=True
r = sr.Recognizer()
def Speech():
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source, duration=1)
print("Say something!")
audio = r.listen(source)
try:
x=r.recognize_google(audio)
print(x)
except sr.UnknownValueError:
pass
except sr.RequestError as e:
pass
while running==True:
r = sr.Recognizer()
with sr.Microphone() as source:
while 1:
Speech()
After hit and trials, I got it right. But I find it slow. If you have better strategy, please comment.
import speech_recognition as sr
running=True
r = sr.Recognizer()
def Speech():
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source, duration=1)
print("Say something!")
audio = r.listen(source)
try:
x=r.recognize_google(audio)
if x=="hello":
print("Speak up")
audio = r.listen(source)
print(r.recognize_google(audio))
except sr.UnknownValueError:
pass
except sr.RequestError as e:
pass
while running==True:
Speech()

Categories

Resources