Python の例 - Amazon Polly

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

Python の例

このガイドには、いくつかの例が用意されています。そのいくつかは、AWS SDK for Python (Boto) を使用して Amazon Polly に API コールを行う Python コード例です。Python をセットアップし、次のセクションに用意されているサンプルコードをテストすることをお勧めします。その他の例については、「アプリケーション例」を参照してください。

Python のセットアップとサンプルのテスト (SDK)

Python サンプルコードをテストするには、AWS SDK for Python (Boto) が必要です。手順については、AWS SDK for Python (Boto3) を参照してください。

Python コード例をテストするには

次の Python コード例は、次のアクションを実行します。

  • AWS SDK for Python (Boto) を使用し、SynthesizeSpeech リクエストを Amazon Polly に送信します (サンプルテキストを入力として指定)。

  • レスポンスで生成された音声ストリームにアクセスし、音声をローカルディスク上のファイル (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])

サンプルアプリケーションなどの追加の例については、「アプリケーション例」を参照してください。