I would like to now how to convert text to speech in python.
In .NET i used
Dim SAPI
Msg = 'Hi this is a test'
SAPI = CreateObject("sapi.spvoice")
SAPI.Speak(Msg)
You can achieve it by pyttsx module. it uses default MS speech recognition system.
import pyttsx
engine = pyttsx.init()
engine.say("Your Message")
engine.runAndWait()
I know its real late to answer here, But I thought I would post here since I have solution based on TTS conversion using SAPI in python, which was OP's original question.
This may be useful for anyone else looking for solution using SAPI in python.
from win32com.client import constants, Dispatch
Msg = "Hi this is a test"
speaker = Dispatch("SAPI.SpVoice") #Create SAPI SpVoice Object
speaker.Speak(Msg) #Process TTS
del speaker #Delete speaker object and free up memory
import pyttsx3
speaker=pyttsx3.init()
speaker.say("Your message")
speaker.runAndWait()
# pip install pywin32
# pip install pyttsx3
import pyttsx3
pyttsx3.speak('Hello Woeld')
You can do it by using the gTTS module. It converts the text to speech.
The second module you have to use is playsound to play the converted text.
from gtts import gTTS #pip install gtts
import playsound #pip install playsound
import os
my_aud = gTTS("hello how are you") #converts the text into speech
my_aud.save('demo.mp3') #save the file with .mp3 extension
playsound('demo.mp3') #to play it
os.remove('demo.mp3')
Here is Male's and Female's voices function created by myself.
Just define a file name and save it.
Now you can import it into another file and reuse it again and again.
pip install pyttsx3
import pyttsx3
def femaleVoice(text):
print("Program : "+text)
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[-1].id)
engine.say(text)
engine.runAndWait()
def maleVoice(text):
print("Program : "+text)
pyttsx3.speak(text)
femaleVoice("There we go.")#Text
maleVoice("There we go.")
If you want access to a ton of voices. We have over 500.
Here's a snippet
python
import apiaudio
import os
apiaudio.api_key = os.environ['APIKEY']
first_track = apiaudio.Orchestrator.create_audio(scriptText="Hello World my first audio track",
voice="Ryan",
soundTemplate="jakarta")
print(first_track)
You just need a FREE api key. Have a look at http://www.api.audio
Related
I try to use speech synthesis in Python 3.9.13 [MSC v.1929 64 bit (AMD64)].
If I understand well, pyttxs3 is the dedicated module (thank you in advance for any possible alternative!), which I installed successfully:
c:\>pip install -U pyttsx3
Requirement already satisfied: pyttsx3 in c:\users\...\python39\site-packages (2.90)
Requirement already satisfied: comtypes in c:\users\...\python39\site-packages (from pyttsx3) (1.1.11)
Requirement already satisfied: pywin32 in c:\users\...\python39\site-packages (from pyttsx3) (304)
Requirement already satisfied: pypiwin32 in c:\users\...\python39\site-packages (from pyttsx3) (223)
but I cannot initialize the engine: when I do
>>> e = pyttsx3.init()
Traceback (most recent call last):
File "C:\Users\...\Python39\site-packages\pyttsx3\__init__.py", line 20, in init
eng = _activeEngines[driverName]
File "C:\Program Files\...\lib\weakref.py", line 137, in __getitem__
o = self.data[key]()
KeyError: None
During handling of the above exception, another exception occurred:
...
File "C:\Users\...\Python39\site-packages\pyttsx3\drivers\sapi5.py", line 10, in <module>
import pythoncom
File "C:\Users\...\Python39\site-packages\pythoncom.py", line 2, in <module>
import pywintypes
ModuleNotFoundError: No module named 'pywintypes'
I noticed that part of the scripts are in my Users\...\AppData\Local\Packages\PythonSoftwareFoundation... and some are in "C:\Program Files\WindowsApps\PythonSoftwareFoundation.... I wonder whether that might be the reason for the errors.
How could I fix this? (I also found that there are other modules, speech and pyttsx, which however appear to be for Python 2.7: they produce Syntax error: print "..." - did you mean print("...")? Is there a Python 3 version of speech or any other alternative?)
pyttxs3 is a little (actually very) glitched for example after i removed a part of my code which involved speaking something it still spoke my old code i removed the whole pyttxs3 from my code it still didn't work at last i had to uninstall the package. I used this function. You need to install pygame (it is a game making package but we will use it) and gtts i.e google text to speech
import os
from pygame import *
from gtts import *
def speak(text: str):
try:
tts_ = gTTS(text=text, lang='en')
ran = random.randint(0, 1000000)
audio_file = 'audio-' + str(ran) + '.mp3'
tts_.save(audio_file)
# Starting the mixer
mixer.init()
# Loading the song
mixer.music.load("C:///Users/roopa/PycharmProjects/pokemon game/" + audio_file)
# Start playing the song
mixer.music.play()
clock = time.Clock()
# infinite loop
while mixer.music.get_busy():
clock.tick(60)
mixer.music.unload()
os.remove(audio_file)
except gTTSError:
print('unknown error')
Roop's answer didn't work out completely for me due to an error "Failed loading libmpg123-0.dll", but it enabled me to find the following working solution:
import gtts # text to mp3 file
import random # for random file name generation
import playsound # to play mp3 file
import os # to remove audio file
def say(text: str, block = True, lang = 'en'):
"""Text-to-speech synthesis using google TTS. If block=True,
waits until the text is spoken. If False, return a cleanup
function to delete the temporary audio file."""
audio_file = f'audio-{random.randint(0, 1000000)}.mp3'
gtts.gTTS(text, lang = lang).save(audio_file)
playsound.playsound(audio_file, block = block)
if block:
os.remove(audio_file)
else:
print(f"Playing sound, don't forget to do: os.remove('{audio_file}')"
"\n(You can do so by calling the returned function.)")
return(lambda: os.remove(audio_file))
if __name__=='__main__':
cleanup = say("Good morning, Max!")
if cleanup: # if block = True, function returns None
import time
time.sleep(10)
cleanup()
(It appears to be a known bug of playsound that the sound isn't played to the end if the script ends too early, therefore I added the sleep(10), but obviously you can do other stuff instead.)
That said, the question regarding pyttsx3 and pywin32 remains open.
I ma trying to run the Audio in loop in google colab but it is not giving mi any output
from gtts import gTTS
from IPython.display import Audio
for voice in ["Aniket","sachin"]:
tts = gTTS("Hello {}".format(voice))
tts.save('1.wav')
sound_file = '1.wav'
Audio(sound_file, autoplay=True)
Output what I want is it should sound hello aniket hello sachin Pleas help
You only need to use "IPython.display.display" method as follows :
from gtts import gTTS
from IPython.display import Audio
from IPython.display import display
for voice in ["Aniket","sachin"]:
tts = gTTS("Hello {}".format(voice))
tts.save('1.wav')
sound_file = '1.wav'
wn = Audio(sound_file, autoplay=True) ##
display(wn)##
you can monkey patch audio to do it piggybacking on the autoplay:
a = Audio(...)
a.autoplay_attr = lambda: 'autoplay="autoplay" loop="loop"'
import pyttsx3
engine=pyttsx3.init('dummy')
engine.say('Hello')
engine.runAndWait()
While I am executing the following code, I am not getting any errors but I am not getting any voice from the system.Help me what I want to do.
This should work:
import pyttsx3
engine = pyttsx3.init()
engine.say("Hello")
engine.runAndWait()
Actually 'dummy' is a test driver that does not do anything. Try using 'sapi5' or leave it empty.
import pyttsx3 engine=pyttsx3.init('sapi5')
(or)
import pyttsx3 engine=pyttsx3.init()
Hope it works!
Hello I have made a code:
from gtts import gTTS
import os
import playsound
from pip._vendor.distlib.compat import raw_input
u = raw_input('type: ')
def player(textg):
tts = gTTS(text = textg, lang='en')
tts.save('name.mp3')
playsound('name.mp3')
player(u)
An error comes that:
playsound('name.mp3')
TypeError: 'module' object is not callable
Please Help Me, i am using Python2.7.15
You're importing the whole module, not a method within it.
You'd need to do something like
from playsound import playsound
case your method is called playsound
you should either import the specific method or call playsound method of the playsound module that you imported already:
playsound.playsound('name.mp3')
Is there a way to get pywin32 to generate a VBA-style MsgBox in Excel, if not, perhaps the Windows equivalent?
I tried:
from win32com.client import Dispatch
excel = Dispatch('Excel.Application')
excel.MsgBox('foo')
but it gives the error below:
AttributeError: Excel.Application.MsgBox
Hi you can use win32api:
import win32api
from win32con import MB_SYSTEMMODAL
response = win32api.MessageBox(0, "Did you hear the Buzzer?", "Buzzer Test", 4, MB_SYSTEMMODAL)
MB_SYSTEMMODAL is used for telling the system to show a message above all other applications.