Skip to content

Instantly share code, notes, and snippets.

@CrashLaker
Last active December 1, 2020 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CrashLaker/0651886c6db23496091c4f83bc17f23f to your computer and use it in GitHub Desktop.
Save CrashLaker/0651886c6db23496091c4f83bc17f23f to your computer and use it in GitHub Desktop.
import json
import boto3
from contextlib import closing
import tempfile
import base64
from io import BytesIO
import random
def lambda_handler(event, context):
# TODO implement
qp = event.get('queryStringParameters', {})
message = qp.get('message', 'hi')
lang = qp.get('lang', 'en-US')
voices = {
'en-US': ['Salli', 'Joanna', 'Matthew', 'Ivy', 'Justin', 'Kendra', 'Kimberly', 'Joey'],
'cmn-CN': ['Zhiyu'],
'es-ES': ['Lucia', 'Enrique', 'Conchita'],
'pt-BR': ['Vitoria', 'Camila', 'Ricardo'],
}
text = f'<speak>{message}</speak>'
c = boto3.client('polly')
rs = c.synthesize_speech(
Engine='standard',
LanguageCode=lang,
OutputFormat='mp3',
Text=text,
TextType='ssml',
VoiceId=random.choice(voices[lang])
)
with closing(rs['AudioStream']) as stream:
body = stream.read()
body = base64.b64encode(body)
body = body.decode('utf8')
return {
'statusCode': 200,
'headers': {
'Content-Type': rs['ContentType'],
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,X-Api-Key,X-Amz-Security-Token',
'Access-Control-Allow-Methods': 'GET',
},
'isBase64Encoded': True,
'body': body
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment