Skip to content

Instantly share code, notes, and snippets.

@nobonobo
Last active December 15, 2015 08:59
Show Gist options
  • Save nobonobo/5235451 to your computer and use it in GitHub Desktop.
Save nobonobo/5235451 to your computer and use it in GitHub Desktop.
喋らせるコマンドラインツール。引数に任意の日本語文字列。
#!/usr/bin/env python
# encoding: utf-8
import sys
import os
import time
import urllib
import urllib2
import tempfile
from PySide import QtCore
from PySide.phonon import Phonon
TTSPEECH_URL = "http://translate.google.com/translate_tts?"
USERAGENT = "Mozilla/5.0 AppleWebKit Safari"
app = QtCore.QCoreApplication([])
app.setApplicationName("Google-Speech")
def speech(text, lang='ja'):
params = urllib.urlencode([('tl', lang),('q', text)])
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', USERAGENT)]
url = TTSPEECH_URL+params
req = urllib2.Request(url)
fd, tmp = tempfile.mkstemp('.mp3')
try:
content = opener.open(req).read()
open(tmp, 'wb').write(content)
m = Phonon.MediaSource(os.path.abspath(unicode(tmp,'utf-8')))
obj = Phonon.createPlayer(Phonon.MusicCategory, m)
obj.play()
while obj.remainingTime():
app.processEvents()
time.sleep(0.1)
finally:
os.remove(tmp)
if __name__ == '__main__':
speech(' '.join(sys.argv[1:]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment