Last active
December 1, 2020 20:04
-
-
Save CrashLaker/0651886c6db23496091c4f83bc17f23f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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