Sorry for the delay. It took me some time to locate the file. This code is horribly direct and was designed to simply mimic the pieces of Google’s translate server that were used by the Sonos plugin. One note, I chose to use the Samantha voice (the new voice of Siri) as I think it sounds much better than other options. Depending on how new your OS is, you might need to download that voice: Add the Voice of Siri to Mac OS X
Obviously to open port 80, you’ll need to execute this script as root, which isn’t a terrific idea of course–but this was for testing. One trick I used to test this without modification to the Sonos plugin code was to add a local IP for translate.google.com to vera’s /etc/hosts file. I wouldn’t recommend that for anything but testing of course.
Final thought: you’ll need lame installed on your mac as well. I used macports for that, but installers for OS X appear to be readily available.
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import os
import urlparse
import tempfile
import subprocess
import shutil
PORT_NUMBER = 80
#http://translate.google.com/translate_tts?tl=%s&q=%s
class voiceProxy(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
parts = urlparse.urlparse(self.path)
text = urlparse.parse_qs(parts.query).get('q', [''])[0]
tmpDir = tempfile.mkdtemp()
try:
aiff_fn = os.path.join(tmpDir, 'translate_tts.aiff')
mp3_fn = os.path.join(tmpDir, 'translate_tts.mp3')
# create an aiff file of the submitted text
p = subprocess.Popen(['say', '-v', 'Samantha', '-o', aiff_fn],
stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
p.stdin.write(text)
out, err = p.communicate()
status = p.wait()
# translate the file to mp3
p = subprocess.Popen(['lame', '-h', '-m', 'm', '-b', '64', aiff_fn, mp3_fn],
stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
out, err = p.communicate()
status = p.wait()
# send it back...
f = open(mp3_fn)
self.send_response(200)
self.send_header('Content-type', "audio/mpeg")
self.end_headers()
self.wfile.write(f.read())
f.close()
finally:
shutil.rmtree(tmpDir, ignore_errors = True)
try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), voiceProxy)
print 'Started httpserver on port ' , PORT_NUMBER
#Wait forever for incoming http requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()