1

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.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
apple_
  • 37
  • 1
  • 8
  • Does this answer your question? [The specified device is not open or is not recognized by MCI](https://stackoverflow.com/questions/68826091/the-specified-device-is-not-open-or-is-not-recognized-by-mci) – Tomerikoo Oct 10 '21 at 10:05
  • The code posted in the question works in Python 3.9. OP seems to have an ENV issue in Windows. – venzen Jan 12 '22 at 01:56

1 Answers1

3

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()
apple_
  • 37
  • 1
  • 8
ksouravdas
  • 124
  • 7
  • I tried this, but the I received an error when trying the `engine = pyttsx3.init()` line: `DLL load failed while importing win32api: The specified module could not be found.` – apple_ Oct 31 '19 at 18:21