Python 示例 - Amazon Polly
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

Python 示例

本指南提供了更多示例,其中一些是使用Amazon SDK for Python (Boto) 对 Amazon Polly 进行 API 调用的 Python 代码示例。我们建议您设置 Python 并测试以下部分中提供的示例代码。有关其他示例,请参阅 示例应用程序

设置 Python 和测试示例 (SDK)

要测试 Python 示例代码,您需要Amazon SDK for Python (Boto)。有关说明,请参阅 Amazon SDK for Python (Boto3)

要测试示例 Python 代码

下面的 Python 代码示例将执行以下操作:

  • 使用Amazon SDK for Python (Boto) 向 Amazon Polly 发送 SynthesizeSpeech 请求(通过提供简单的文本作为输入)。

  • 访问在响应中生成的音频流并将音频保存为您本地磁盘上的文件 (speech.mp3)。

  • 使用您的本地系统的默认音频播放器播放音频文件。

将代码保存为一个文件 (example.py) 并运行。

"""Getting Started Example for Python 2.7+/3.3+""" from boto3 import Session from botocore.exceptions import BotoCoreError, ClientError from contextlib import closing import os import sys import subprocess from tempfile import gettempdir # Create a client using the credentials and region defined in the [adminuser] # section of the Amazon credentials file (~/.aws/credentials). session = Session(profile_name="adminuser") polly = session.client("polly") try: # Request speech synthesis response = polly.synthesize_speech(Text="Hello world!", OutputFormat="mp3", VoiceId="Joanna") except (BotoCoreError, ClientError) as error: # The service returned an error, exit gracefully print(error) sys.exit(-1) # Access the audio stream from the response if "AudioStream" in response: # Note: Closing the stream is important because the service throttles on the # number of parallel connections. Here we are using contextlib.closing to # ensure the close method of the stream object will be called automatically # at the end of the with statement's scope. with closing(response["AudioStream"]) as stream: output = os.path.join(gettempdir(), "speech.mp3") try: # Open a file for writing the output as a binary stream with open(output, "wb") as file: file.write(stream.read()) except IOError as error: # Could not write to file, exit gracefully print(error) sys.exit(-1) else: # The response didn't contain audio data, exit gracefully print("Could not stream audio") sys.exit(-1) # Play the audio using the platform's default player if sys.platform == "win32": os.startfile(output) else: # The following works on macOS and Linux. (Darwin = mac, xdg-open = linux). opener = "open" if sys.platform == "darwin" else "xdg-open" subprocess.call([opener, output])

有关其他示例,包括示例应用程序,请参阅 示例应用程序