Polly返回0字节

2024-06-02 14:07:44 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试通过AWS polly执行基本tts任务时,我可以使用CLI通过以下命令类型获得可播放的mp3:

aws polly synthesize-speech --output-format mp3 --voice-id Joanna --text 'Hello, my name is Joanna. I learned about the W3C on 10/3 of last year.' hello.mp3


但是,按照提供的示例here,我将返回0字节的mp3文件。

我的代码:

from boto3 import Session
from botocore.exceptions import BotoCoreError, ClientError
from contextlib import closing
import os
import sys
import subprocess
from tempfile import gettempdir
session = Session(profile_name="default")
polly = session.client("polly")

try:
    response = polly.synthesize_speech(Text="This is what you wrote. It'd be cool if it also 
worked.",
                                    OutputFormat="mp3",
                                    VoiceId="Joanna",
                                    )
except (BotoCoreError, ClientError) as error:
    print(error)
    sys.exit(-1)

if "AudioStream" in response:
    with closing(response["AudioStream"]) as stream:
        output = ("speech.mp3")
        print(os.path.join(gettempdir(), "hopa"))
    try:
        with open(output, "wb") as file:
            file.write(stream.read())
    except IOError as error:
        print(error)
        sys.exit(-1)
else:
    print("Could not stream audio")
    sys.exit(-1)

os.startfile(output)

Tags: fromimportoutputstreamosresponseassys
1条回答
网友
1楼 · 发布于 2024-06-02 14:07:44

您在with中的缩进不正确

这项工作:

import boto3
from botocore.exceptions import BotoCoreError, ClientError
from contextlib import closing
import sys
polly = boto3.client("polly")

try:
    response = polly.synthesize_speech(
        Text="This is what you wrote. It'd be cool if it also worked.",
        OutputFormat="mp3",
        VoiceId="Joanna",
    )
except (BotoCoreError, ClientError) as error:
    print(error)
    sys.exit(-1)

if "AudioStream" in response:
    with closing(response["AudioStream"]) as stream:
        output = "speech.mp3"
        try:
            with open(output, "wb") as file:
                file.write(stream.read())
        except IOError as error:
            print(error)
            sys.exit(-1)
else:
    print("Could not stream audio")
    sys.exit(-1)

相关问题 更多 >