in tts/tts/services/amazonpolly.py [0:0]
def _synthesize_speech_and_save(self, request):
"""
Call Amazon Polly and writes the returned audio data to a local file.
To make it practical, three things will be returned in a JSON form string, which are audio file path,
audio type and Amazon Polly response metadata.
If the Amazon Polly call fails, audio file name will be an empty string and audio type will be "N/A".
Please see https://boto3.readthedocs.io/reference/services/polly.html#Polly.Client.synthesize_speech
for more details on Amazon Polly API.
:param request: an instance of Polly.Request
:return: a string in JSON form with two attributes, "Audio File" and "Amazon Polly Response".
"""
kws = {
'LexiconNames': request.lexicon_names if request.lexicon_names else [],
'OutputFormat': request.output_format if request.output_format else self.default_output_format,
'SampleRate': request.sample_rate,
'SpeechMarkTypes': request.speech_mark_types if request.speech_mark_types else [],
'Text': request.text,
'TextType': request.text_type if request.text_type else self.default_text_type,
'VoiceId': request.voice_id if request.voice_id else self.default_voice_id
}
if not kws['SampleRate']:
kws['SampleRate'] = '16000' if kws['OutputFormat'].lower() == 'pcm' else '22050'
self.loginfo('Amazon Polly Request: {}'.format(kws))
response = self.polly.synthesize_speech(**kws)
self.loginfo('Amazon Polly Response: {}'.format(response))
if "AudioStream" in response:
audiofile = self._make_audio_file_fullpath(request.output_path, kws['OutputFormat'])
self.loginfo('will save audio as {}'.format(audiofile))
with closing(response["AudioStream"]) as stream:
if kws['OutputFormat'].lower() == 'pcm':
self._pcm2wav(stream.read(), audiofile, kws['SampleRate'])
else:
with open(audiofile, "wb") as f:
f.write(stream.read())
audiotype = response['ContentType']
else:
audiofile = ''
audiotype = 'N/A'
return json.dumps({
'Audio File': audiofile,
'Audio Type': audiotype,
'Amazon Polly Response Metadata': str(response['ResponseMetadata'])
})