Created
January 31, 2013 21:41
-
-
Save anonymous/4686762 to your computer and use it in GitHub Desktop.
Assist in performing online Text-To-Speech and immediate playback.
This file contains 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
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment