Skip to content
Create a gist now

Instantly share code, notes, and snippets.

anonymous /

Assist in performing online Text-To-Speech and immediate playback.
#!/usr/bin/env python
Assist in performing online Text-To-Speech and immediate playback.
import sys
import requests
import urllib
import tempfile
import commands
import locale
LC = locale.getdefaultlocale()[0] or 'en'
def google_tts(text, fh):
Has Google perform Text-To-Speech on text, writing to fh.
for line in chop(text, 100):
url = "" \
% tuple(map(urllib.quote_plus, [LC, line]))
# MPEG streams can be concatenated
print 'TTS Line:', line
def mplayer(filename):
commands.getoutput('mplayer ' + filename)
def chop(text, size=100):
Chops up text in parts of at most size, separating at natural pauses.
splitlist = ['.?!', ',:;()"', ' ']
while len(text) > size:
subtext = text[:size]
for splitters in splitlist:
sep = max(map(subtext.rfind, splitters))
if sep >= 0:
if sep == -1:
sep = size-1
yield text[:sep+1]
text = text[sep+1:].lstrip()
if len(text) > 0:
yield text
def say(text, tts=google_tts, playback=mplayer):
Pronounces text as speech using the given methods.
text = ' '.join(text.split())
fh = tempfile.NamedTemporaryFile()
tts(text, fh)
if __name__ == '__main__':
args = sys.argv[1:]
if len(args) > 0 and args[0].startswith('-'):
LC = args[0][1:]
args = args[1:]
if len(args) == 0:
text =
text = ' '.join(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.