I'm trying to find the best way to play a sound in Python without downloading any sound files (eg using temporary files with tempfile
). This is for a speak
function using gTTS
; I've already come up with a solution to save the voice file to a NamedTemporaryFile
object. The trouble I've had is trying to play it:
from gtts import gTTS
from tempfile import TemporaryFile
def speak(text, lang = 'en'):
gTTS(text=text, lang=lang).write_to_fp(voice := TemporaryFile())
#Play voice
voice.close()
I just need something to replace #Play voice
here, this is the solution I tried:
from gtts import gTTS
from tempfile import NamedTemporaryFile
from playsound import playsound
def speak(text, lang='en'):
gTTS(text=text, lang=lang).write_to_fp(voice := NamedTemporaryFile())
playsound(voice.name)
voice.close()
This returns an error:
The specified device is not open or is not recognized by MCI.
Note: The solution doesn't HAVE to use any of the above modules BESIDES gTTS. As long as the speak
function can be used repeatedly and without saving any files, it's good enough.