gpt4 book ai didi

python - 转换python espeak + subprocess代码直接播放输出音频

转载 作者:太空宇宙 更新时间:2023-11-04 09:22:23 25 4
gpt4 key购买 nike

我正在使用一个现有程序,该程序从套接字读取 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 文件?

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

How to use python Popen with a espeak and aplay

最佳答案

您可以使用 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()

在发送要说的消息后,关闭procstdin 很重要。这将使 proc 在发送数据后退出,并关闭其对 aplay 的输出,而 aplay 则在播放结束后退出。如果 proc 的输入没有关闭,它们都不会退出。

关于python - 转换python espeak + subprocess代码直接播放输出音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40446146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com