Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save file as mp3 from Amazon Polly using Python

I am using Amazon Polly for TTS, but I am not able to get how to save the converted speech into a .mp3 file in my computer

I have tried gTTS but i require Amazon Polly for my task.

import boto3
client = boto3.client('polly')
response = client.synthesize_speech
(Text = "Hello my name is Shubham", OuptutFormat = "mp3", VoiceId = 'Aditi')

Now, what Should I do to play this converted speech or save it into my PC as .mp3 file?

like image 369
Shubham Verma Avatar asked Oct 22 '25 15:10

Shubham Verma


2 Answers

This code sample is taken straight from the documentation: https://docs.aws.amazon.com/polly/latest/dg/SynthesizeSpeechSamplePython.html

import boto3

polly_client = boto3.Session(
                aws_access_key_id=,                     
    aws_secret_access_key=,
    region_name='us-west-2').client('polly')

response = polly_client.synthesize_speech(VoiceId='Joanna',
                OutputFormat='mp3', 
                Text = 'This is a sample text to be synthesized.')

file = open('speech.mp3', 'wb')
file.write(response['AudioStream'].read())
file.close()
like image 174
Paul M. Avatar answered Oct 25 '25 04:10

Paul M.


While not directly related to the original question, I responded to one of the comments about hot to get to the audio stream without saving the audio to a file.

You might also check out the documentation for this example: https://docs.aws.amazon.com/polly/latest/dg/example-Python-server-code.html

This shows getting the response back from Polly:

    response = polly.synthesize_speech(Text=text, VoiceId=voiceId, OutputFormat=outputFormat)
    data_stream=response.get("AudioStream")

The first line makes the request to Polly and stores the response in the response object, while the second line gets the audio stream from the response object.

like image 40
Chris Hare Avatar answered Oct 25 '25 05:10

Chris Hare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!