Python TTS (Text To Speech) with AWS Polly

From PedrosBrainDump
# importing libs
import boto3
import logging

# Initialize the Polly client
polly_client = boto3.client('polly')

def awsPollyTTS(input_text, output_file_name="output.mp3", voice_id='Joanna', output_format='mp3'):
    try:
        # Request speech synthesis from AWS Polly
        response = polly_client.synthesize_speech(
            Text=text,
            VoiceId=voice_id,
            OutputFormat=output_format,
            SampleRate='22050'
        )

        # Get the audio stream from the response
        audio_stream = response.get('AudioStream')

        # Write the audio stream to a file (in this case, an MP3 file)
        with open(output_file_name, 'wb') as audio_file:
            audio_file.write(audio_stream.read())
        print(f"Speech synthesis complete. The audio is saved as '{output_file_name}'.")

    except Exception as e:
        logging.error(f"Error synthesizing speech: {e}")
        print(f"Error synthesizing speech: {e}")