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()
Related
So i have a voice assistant project i use speech recognition and pytsx3, the problem is the functions repetition, so this is my code
main.py:
import possibilities as ps
clear = lambda: os.system('cls')
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[3].id)
engine.setProperty("rate", 160)
def speak(audio):
engine.say(audio)
engine.runAndWait()
while True:
rec = sr.Recognizer()
with sr.Microphone() as mic:
print("Manini listen...")
audio = rec.listen(mic)
try:
text = rec.recognize_google(audio, language='en')
query = text.lower()
except Exception as e:
print("Manini Listen...")
if 'wikipedia' in query:
ps.wikipediaSer(query)
elif "say" in query:
ps.sayrep(query)
elif 'open youtube' in query:
ps.openyoutube()
possibilties.py:
def wikipediaSer(query):
speak('Searching Wikipedia...')
query = query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences = 2)
speak("According to Wikipedia")
print(results)
speak(results)
def sayrep(query):
say_text = query.replace("say", "")
speak(say_text)
def openyoutube():
speak("Here you go to Youtube\n")
webbrowser.open("youtube.com")
so when I execute the project and say a command Wikipedia par example, Wikipedia code repet 5 times. how I can fix this repetition please.
'''
on executing the following code, when I am giving any instruction to this voice assistant :
it is not printing whatever i am saying
it is opening myntra's website for every instruction I am giving
'''
import pyttsx3 #text to speech
import speech_recognition as sr #recognizes speech
import wikipedia
import webbrowser
import datetime
import os
import smtplib
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id) #activates voice
def speak(audio):
# enables system to speak
engine.say(audio)
engine.runAndWait()
def wishme():
to take know the current time
hour = int(datetime.datetime.now().hour)
if hour >= 00 and hour < 12:
speak("good morning!")
elif hour >= 12 and hour < 18:
speak("good afternoon!")
else:
speak("good evening!")
speak("I am JARVIS sir , how may i help you ?")
def takeCommand():
'''It takes microphone input from user and returns string output'''
# I added r.adjust_for_ambient_noise(source) and reduced threshold frequency
r = sr.Recognizer() # to recognize the user's voice
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1
r.energy_threshold = 50 #to listen low frequency voices
r.adjust_for_ambient_noise(source) #to avoid noise
audio = r.listen(source)
try:
print("Recognizing...")
# to recognize user's voice
query = r.recognize_google(audio , Language = "en-in")
print(f"user said: {query}\n")
except Exception as e:
print("Say that again please...")
return "None"
return query
if __name__ == "__main__":
# speak("Akshima is a good girl")
wishme()
while True:
query = takeCommand().lower()
# logic for executing tasks based on query
# maybe there is an error in this part of the code
if 'wikipedia' in query:
speak('Searching Wikipedia...')
query = query.replace("wikipedia", "")
result = wikipedia.summary(query, sentences=2)
speak("according to wikipedia")
print(result)
speak(result)
elif 'open youtube' in query:
# to open youtube
webbrowser.open("youtube.com")
elif 'open google' in query:
webbrowser.open("google.com") #to open google
elif 'play music' in query:
webbrowser.open("spotify.com")
elif 'open myntra' or 'open any online shopping site ' in query:
webbrowser.open("myntra.com")
elif 'open instagram' in query:
webbrowser.open("instagram.com")
elif 'chill' in query:
webbrowser.open("netflix.com")
elif "the time" in query:
# tell user the current time
strTime = datetime.datetime.now().srtftime("%H:%M:%S")
speak(f"The time is {strTime}\n")
elif 'open code' in query:
#to open vs code
path = "C:\\Users\\HP\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
os.startfile(path)
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()
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)
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()