0

我正在使用一个现有的程序,它从套接字读取 xml,将文本转换为 wav 文件,然后在音频输出设备上播放它。

我想将其剥离,以便将文本直接播放到音频中。

现在我很难弄清楚我是否有正确的代码并理解它是否真的在创建 wav 文件。

调用调用文本到语音函数的函数

def generate_audio(self, language, voice=None):
    info = self.get_first_info(language, bestmatch=False)
    if info is None:
        self.media_info[language] = None
        return False

    truncate = not self.broadcast_immediately() and bcastplayer.Config.setting('alerts_truncate')
    message_text = info.get_message_text(truncate)

    location = bcastplayer.ObData.get_datadir() + "/alerts"
    if os.access(location, os.F_OK) == False:
        os.mkdir(location)
    filename = self.reference(self.sent, self.identifier) + "-" + language + ".wav"

    resources = info.get_resources('audio')
    if resources:
        if resources[0].write_file(os.path.join(location, filename)) is False:
            return False

    elif message_text:
        self.write_tts_file(os.path.join(location, filename), message_text, voice)

    else:
        return False

可以修改为直接播放音频吗?

def write_tts_file(self, path, message_text, voice=None):
    if not voice:
        voice = 'en'
    proc = subprocess.Popen([ 'espeak', '-m', '-v', voice, '-s', '130', '--stdout' ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
    (stdout, stderr) = proc.communicate(message_text.encode('utf-8') + b" <break time=\"2s\" /> " + message_text.encode('utf-8') + b" <break time=\"3s\" /> ")
    proc.wait()

    with open(path, 'wb') as f:
        f.write(stdout)

我从未见过这样使用process, subprocess, stdout, 的代码PIPE

aplay在不创建 wav 文件的情况下将子进程代码更改为仅通过管道传输或将输出重定向到的内容是否容易?

还有另一个答案可能会提供线索-但同样,我的新手理解不确定如何将此代码转换为该答案

如何将 python Popen 与 espeak 和 aplay 一起使用

4

1 回答 1

2

您可以使用 将这两个进程链接在一起subprocess.PIPE。这是该write_tts_file函数的修改版本:

def write_tts_file(self, path, message_text, voice=None):
    if not voice:
        voice = 'en'
    proc = subprocess.Popen(['espeak', '-m', '-v', voice, '-s', '130', '--stdout' ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
    aplay = subprocess.Popen(['aplay', '-D', 'sysdefault'], stdin=proc.stdout)
    proc.stdin.write(message_text.encode('utf-8') + b" <break time=\"2s\" /> " + message_text.encode('utf-8') + b" <break time=\"3s\" /> \n")
    proc.stdin.close()
    proc.wait()

在您发送要说的消息后关闭proc's很重要。stdin这将proc在它发送完数据后退出,并关闭它的输出到aplay,然后在播放完毕后退出。如果proc' 的输入没有关闭,它们都不会退出。

于 2016-11-07T21:08:08.780 回答