PageRenderTime 55ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/saythis.py

https://gitlab.com/manufacturaind/saythis
Python | 86 lines | 49 code | 8 blank | 29 comment | 4 complexity | ac121c98d40c8d4d469aee8b12b77bb1 MD5 | raw file
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Saythis.py
  4. #
  5. # Multilanguage TTS courtesy of Google Translate
  6. # (C) Manufactura Independente 2011
  7. # Released under the terms of the GPL v3
  8. # http://www.gnu.org/licenses/gpl.html
  9. #
  10. # Based on the hints given here:
  11. # http://lifehacker.com/5426797/google-translate-url-generates-instant-text+to+speech-mp3-files
  12. #
  13. # Usage:
  14. # saythis.py "Say this!"
  15. #
  16. # Quotes can be omitted too:
  17. # saythis.py Say this!
  18. #
  19. # You can also specify the language:
  20. # saythis.py "Pimbas!" --lang pt
  21. #
  22. # Output to a file instead of playing it:
  23. #
  24. # saythis.py "Pimbas!" --lang pt --output pimbas.mp3
  25. #
  26. # TODO:
  27. # - List available languages
  28. DEFAULT_LANGUAGE = 'en'
  29. DEFAULT_TEMP_FILE = '/tmp/test.mp3'
  30. DEFAULT_PLAY_COMMAND = 'mplayer %s'
  31. import sys, os
  32. import urllib
  33. lang = 'pt'
  34. # we create a custom URL opener because Google only accepts Mozilla user agents
  35. class AppURLopener(urllib.FancyURLopener):
  36. version = "Mozilla"
  37. urllib._urlopener = AppURLopener()
  38. if not len(sys.argv) > 1:
  39. print "I need a string to speak!"
  40. sys.exit()
  41. saythis = sys.argv[1]
  42. def tts(saythis, outfile, lang):
  43. url = "http://translate.google.com/translate_tts?ie=UTF-8&q=%s&tl=%s&prev=input" % (urllib.quote(saythis), lang)
  44. try:
  45. urllib.urlretrieve (url, outfile)
  46. except IOError:
  47. print 'Received IOError -- are you online?'
  48. sys.exit()
  49. if __name__ == '__main__':
  50. # analisar as opções da linha de comandos
  51. import optparse
  52. parser = optparse.OptionParser()
  53. parser.add_option('-l', '--lang',
  54. dest="lang",
  55. default="Specify language (default: en)",
  56. help=''
  57. )
  58. parser.add_option('-o', '--output',
  59. dest="output",
  60. default="",
  61. help='Save to specified file (MP3 format) instead of playing a sound'
  62. )
  63. options, remainder = parser.parse_args()
  64. lang = options.lang
  65. outfile = options.output
  66. saythis = ' '.join(remainder)
  67. if not outfile:
  68. outfile = DEFAULT_TEMP_FILE
  69. speak = True
  70. if not lang:
  71. lang = DEFAULT_LANGUAGE
  72. tts(saythis, outfile, lang)
  73. if speak:
  74. os.system(DEFAULT_PLAY_COMMAND % outfile)
  75. os.remove(outfile)