Encapsulates Amazon Polly functions.
| 19 | |
| 20 | # snippet-start:[python.example_code.polly.helper.PollyWrapper] |
| 21 | class PollyWrapper: |
| 22 | """Encapsulates Amazon Polly functions.""" |
| 23 | |
| 24 | def __init__(self, polly_client, s3_resource): |
| 25 | """ |
| 26 | :param polly_client: A Boto3 Amazon Polly client. |
| 27 | :param s3_resource: A Boto3 Amazon Simple Storage Service (Amazon S3) resource. |
| 28 | """ |
| 29 | self.polly_client = polly_client |
| 30 | self.s3_resource = s3_resource |
| 31 | self.voice_metadata = None |
| 32 | |
| 33 | # snippet-end:[python.example_code.polly.helper.PollyWrapper] |
| 34 | |
| 35 | # snippet-start:[python.example_code.polly.DescribeVoices] |
| 36 | def describe_voices(self): |
| 37 | """ |
| 38 | Gets metadata about available voices. |
| 39 | |
| 40 | :return: The list of voice metadata. |
| 41 | """ |
| 42 | try: |
| 43 | response = self.polly_client.describe_voices() |
| 44 | self.voice_metadata = response["Voices"] |
| 45 | logger.info("Got metadata about %s voices.", len(self.voice_metadata)) |
| 46 | except ClientError: |
| 47 | logger.exception("Couldn't get voice metadata.") |
| 48 | raise |
| 49 | else: |
| 50 | return self.voice_metadata |
| 51 | |
| 52 | # snippet-end:[python.example_code.polly.DescribeVoices] |
| 53 | |
| 54 | # snippet-start:[python.example_code.polly.Synthesize] |
| 55 | def synthesize( |
| 56 | self, text, engine, voice, audio_format, lang_code=None, include_visemes=False |
| 57 | ): |
| 58 | """ |
| 59 | Synthesizes speech or speech marks from text, using the specified voice. |
| 60 | |
| 61 | :param text: The text to synthesize. |
| 62 | :param engine: The kind of engine used. Can be standard or neural. |
| 63 | :param voice: The ID of the voice to use. |
| 64 | :param audio_format: The audio format to return for synthesized speech. When |
| 65 | speech marks are synthesized, the output format is JSON. |
| 66 | :param lang_code: The language code of the voice to use. This has an effect |
| 67 | only when a bilingual voice is selected. |
| 68 | :param include_visemes: When True, a second request is made to Amazon Polly |
| 69 | to synthesize a list of visemes, using the specified |
| 70 | text and voice. A viseme represents the visual position |
| 71 | of the face and mouth when saying part of a word. |
| 72 | :return: The audio stream that contains the synthesized speech and a list |
| 73 | of visemes that are associated with the speech audio. |
| 74 | """ |
| 75 | try: |
| 76 | kwargs = { |
| 77 | "Engine": engine, |
| 78 | "OutputFormat": audio_format, |
no outgoing calls