【问题标题】:How do you play sound directly in python?你如何在python中直接播放声音?
【发布时间】:2020-02-27 03:17:06
【问题描述】:

我正在尝试寻找在 Python 中播放声音而不下载任何声音文件的最佳方式(例如,使用带有tempfile 的临时文件)。这是针对使用gTTSspeak 函数;我已经想出了将语音文件保存到NamedTemporaryFile 对象的解决方案。我遇到的麻烦是尝试播放它:

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()

我只需要在这里替换#Play voice,这是我尝试过的解决方案:

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()

这会返回一个错误:

The specified device is not open or is not recognized by MCI.

注意:除了 gTTS 之外,该解决方案不必使用上述任何模块。只要speak函数可以重复使用,不保存任何文件,就足够了。

【问题讨论】:

标签: python audio gtts python-playsound


【解决方案1】:

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

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

【讨论】:

  • 我试过这个,但我在尝试engine = pyttsx3.init() 行时收到错误:DLL load failed while importing win32api: The specified module could not be found.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-08
  • 2015-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多