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.

4

1 回答 1

2

您应该使用pyttsx3而不是gtts. 无需保存语音片段,因为语音会在运行时直接播放。您可以在此处找到详细信息:https ://pypi.org/project/pyttsx3/

import pyttsx3
engine = pyttsx3.init()
engine.say("I will speak this text")
engine.runAndWait()
于 2019-10-31T17:55:22.230 回答