Search code examples
pythonamazon-web-servicesboto3text-to-speechamazon-polly

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?


Solution

  • 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()