pythonaudiogttspython-playsound

How do you play sound directly in python?


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.


Solution

  • You should use pyttsx3 instead of gtts. There's no need to save the voice clip, because the voice will directly play at runtime. You can find details here: https://pypi.org/project/pyttsx3/

    import pyttsx3
    engine = pyttsx3.init()
    engine.say("I will speak this text")
    engine.runAndWait()