How to play Audio in loop in Google colab - python

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"'

Related

Python text to speech not working using pyttsx3

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!

AttributeError: module 'utils' has no attribute 'get_audio_path'

I am engaging a project now, and the library utils might be frequently used. However, I just cannot normally invoke functions from utils. See code below.
import IPython.display as ipd
import librosa
import librosa.display
import utils
filename = utils.get_audio_path(AUDIO_DIR, 2)#AUDIO_DIR is an audio path
print('File: {}'.format(filename))
x, sr = librosa.load(filename, sr=None, mono=True)
print('Duration: {:.2f}s, {} samples'.format(x.shape[-1] / sr, x.size))
start, end = 7, 17
ipd.Audio(data=x[start*sr:end*sr], rate=sr)
Plus, I had installed library python_utils either, but didn't work.

Python WinSound: Runtime Error after writing to wav

I'm trying to make a program that plays text-to-speech with gTTS.
import gtts
import winsound
import time
def playtts(strin):
fl = gtts.gTTS(text = strin, lang = 'en')
fl.save('temp.wav')
time.sleep(3)
winsound.PlaySound('temp.wav', winsound.SND_FILENAME | winsound.SND_NOSTOP | winsound.SND_NODEFAULT)
playtts("HELLO THERE")
When I run it, I get:
File "[DATA EXPUNGED]", line 14, in <module>
playtts("HELLO THERE")
File "[DATA EXPUNGED]", line 12, in playtts
winsound.PlaySound('temp.wav', winsound.SND_FILENAME | winsound.SND_NOSTOP | winsound.SND_NODEFAULT)
RuntimeError: Failed to play sound
>>>
When I open the file in Media Player, it works just fine. Why is it raising errors?
import gtts
import winsound
import time,os
def playtts(strin):
fl = gtts.gTTS(text = strin, lang = 'en')
fl.save('temp.wav')
time.sleep(3)
os.system("start temp.wav")
playtts("whiskers whats up")
Here's a way to do it without winsound it opens a media player and then plays it for you and you.

How to display a heatmap created in python using rpy2?

I am currently trying to generate a heatmap in python from a text file, using R commands (with rpy2). It works fine in R, but when I take it to python, the Quartz interface displays quickly and then closes. I would like either to be able to save the quartz display to a file, or directly save my heatmap to a file without displaying it.
Here is the code I have been using:
import rpy2.robjects as robjects
robjects.r('''
library("gplots")
data = read.csv("/Users/.../Heatmap_data.txt")
DF = data.frame(data)
MD = data.matrix(DF,rownames.force=NA)
heatmap.2(MD, scale="none", col=redgreen(100), cexRow=0.1, key=FALSE, symkey=FALSE, trace="none", Colv=FALSE)
''')
I'm using python 2.7, on OS X Yosemite.
Thank you for any help.
import numpy as np
import rpy2.robjects as ro
import rpy2.robjects.numpy2ri
ro.numpy2ri.activate()
R = ro.r
data = np.random.random((10, 10))
R.png(file='/tmp/out.png')
R.heatmap(data)
R("dev.off()")
writes to the file /tmp/out.png without displaying the image:
.
Preventing the displayed image from immediately closing can be done like this:
script.py:
import numpy as np
import rpy2.robjects as ro
import rpy2.robjects.numpy2ri
import rpy2.rinterface as rinterface
import time
import threading
ro.numpy2ri.activate()
R = ro.r
def ion():
def r_refresh(interval = 0.03):
while True:
rinterface.process_revents()
time.sleep(interval)
t = threading.Thread(target=r_refresh)
t.daemon = True
t.start()
ion()
data = np.random.random((10, 10))
R.heatmap(data)
R("dev.copy(png,'/tmp/out2.png')")
R("dev.off()")
try:
# for Python2
raw_input()
except NameError:
# for Python3
input()
The raw_input or input call prevents the Python interpreter from exiting, thus allowing the window to stay open, until the user presses Enter.
The ion function calls rinterface.process_revents() periodically so the
displayed window will react to GUI events such as resizing or being closed.
dev.copy(png,'/tmp/out2.png') saves the already-displayed image to a
file.

How to convert text to speech in python

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

Categories