Want more features on Pastebin? Sign Up, it's FREE!
Guest

Google TTS results

By: a guest on Aug 28th, 2011  |  syntax: Python  |  size: 1.86 KB  |  views: 642  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #!/usr/bin/python
  2. #-*- mode: python; coding: utf-8 -*-
  3. import urllib, urllib2
  4. from os import path
  5.  
  6. def get_tts_mp3( lang, sent, fname=None ):
  7.     print "Retrieving .mp3 for sentence: %s" % sent
  8.     baseurl  = "http://translate.google.com/translate_tts"
  9.     values   = { 'q': sent, 'tl': lang }
  10.     data     = urllib.urlencode(values)
  11.     request  = urllib2.Request(baseurl, data)
  12.     request.add_header("User-Agent", "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11" )
  13.     response = urllib2.urlopen(request)
  14.     if( fname==None ):
  15.         fname = "_".join(sent.split())
  16.     ofp = open(fname,"wb")
  17.     ofp.write(response.read())
  18.     print "Saved to file: %s" % fname
  19.     return
  20.  
  21. def parse_list_from_file( lang, infile ):
  22.     ifp = open(infile)
  23.     for line in ifp:
  24.         line = line.strip()
  25.         get_tts_mp3( lang, line, fname=line+".mp3" )
  26.     ifp.close()
  27.     return
  28.  
  29. if __name__=="__main__":
  30.     import sys, argparse
  31.  
  32.     example = "%s --lang ja --sent 日本語は難しい --fname outfile.mp3" % sys.argv[0]
  33.  
  34.     parser  = argparse.ArgumentParser( description=example )
  35.     parser.add_argument('--lang',   "-a", help='Input language abbreviation: Korean=kr, Japanese=ja, English=en, etc.', required=True )
  36.     parser.add_argument('--sent',   "-s", help='An input sentence to synthesize.', default=None )
  37.     parser.add_argument('--slist',  "-l", help='A file with a list of sentences to synthesize, one per line.', default=None )
  38.     parser.add_argument('--fname',  "-f", help='Output filename, defaults to the input sentence .mp3', default=None )
  39.     args = parser.parse_args()
  40.    
  41.     if not args.sent==None:
  42.         get_tts_mp3( args.lang, args.sent, args.fname )
  43.     elif not args.slist==None:
  44.         parse_list_from_file( args.lang, args.slist )
  45.     else:
  46.         print "Please supply either a value for either --sent or --slist."
clone this paste RAW Paste Data