Python TTS (Text To Speech) with AWS Polly

From PedrosBrainDump
Revision as of 20:43, 1 January 2025 by 413vhcu1lq0463ob (talk | contribs) (Created page with " # 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' )...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
# 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}")