Python 예제 - Amazon Polly

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Python 예제

이 가이드에서는 Amazon Polly에 API를 호출하는 AWS SDK for Python (Boto) 데 사용하는 몇 가지 Python 코드 예제를 제공합니다. 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])

예제 애플리케이션을 포함한 추가 예제는 애플리케이션의 예을 참조하세요.