public
anonymous / say.py
Created

Assist in performing online Text-To-Speech and immediate playback.

  • Download Gist
say.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
#!/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 = "http://translate.google.com/translate_tts?ie=UTF-8&tl=%s&q=%s" \
% tuple(map(urllib.quote_plus, [LC, line]))
# MPEG streams can be concatenated
fh.write(requests.get(url).content)
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:
break
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)
fh.flush()
playback(fh.name)
fh.close()
 
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 = sys.stdin.read()
else:
text = ' '.join(args)
say(text)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.