Skip to content

Instantly share code, notes, and snippets.

@catqbat
Last active November 29, 2017 16:45
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 catqbat/bd0ccbc1d527709ca2d42da7e7f96bba to your computer and use it in GitHub Desktop.
Save catqbat/bd0ccbc1d527709ca2d42da7e7f96bba to your computer and use it in GitHub Desktop.
python library for Amazon Polly
import boto3
import pygame
import os
import time
import io
class Polly():
OUTPUT_FORMAT='mp3'
def __init__(self, voiceId):
self.polly = boto3.client('polly') #access amazon web service
self.VOICE_ID = voiceId
def say(self, textToSpeech): #get polly response and play directly
pollyResponse = self.polly.synthesize_speech(Text=textToSpeech, OutputFormat=self.OUTPUT_FORMAT, VoiceId=self.VOICE_ID)
pygame.mixer.init()
pygame.init() # this is needed for pygame.event.* and needs to be called after mixer.init() otherwise no sound is played
if os.name != 'nt':
pygame.display.set_mode((1, 1)) #doesn't work on windows, required on linux
with io.BytesIO() as f: # use a memory stream
f.write(pollyResponse['AudioStream'].read()) #read audiostream from polly
f.seek(0)
pygame.mixer.music.load(f)
pygame.mixer.music.set_endevent(pygame.USEREVENT)
pygame.event.set_allowed(pygame.USEREVENT)
pygame.mixer.music.play()
pygame.event.wait() # play() is asynchronous. This wait forces the speaking to be finished before closing
while pygame.mixer.music.get_busy() == True:
pass
def saveToFile(self, textToSpeech, fileName): #get polly response and save to file
pollyResponse = self.polly.synthesize_speech(Text=textToSpeech, OutputFormat=self.OUTPUT_FORMAT, VoiceId=self.VOICE_ID)
with open(fileName, 'wb') as f:
f.write(pollyResponse['AudioStream'].read())
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment