Python 範例 - Amazon Polly

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

Python 範例

本指南提供一些 Python 程式碼範例,可用 AWS SDK for Python (Boto) 來對 Amazon Polly 進行 API 呼叫。建議您設定 Python 並測試下節中提供的範例程式碼。如需額外的範例,請參閱應用範例

設定 Python 並測試範例 (SDK)

若要測試 Python 範例程式碼,您需要 AWS SDK for Python (Boto)。如需相關指示,請參閱AWS SDK for Python (Boto3)

測試 Python 程式碼範例

以下 Python 程式碼範例會執行下列動作:

  • 調用 AWS 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 AWS 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])

如需其他範例包括範例應用程式的詳細資訊,請參閱應用範例