acapela.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import sha
  2. import os
  3. import shutil
  4. import pygame
  5. import requests
  6. import logging
  7. VOXYGEN_LANGUAGES = {
  8. "fr" : {"electra":"Electra","emma":"Emma","becool":"Becool","agnes":"Agnes","loic":"Loic","fabienne":"Fabienne","helene":"Helene","marion":"Marion","matteo":"Matteo","melodine":"Melodine","mendoo":"Mendoo","michel":"Michel","moussa":"Moussa","philippe":"Philippe","sorciere":"Sorciere"},
  9. "ar" : {"adel":"Adel"},
  10. "de" : {"matthias":"Matthias","jylvia":"Sylvia"},
  11. "uk" : {"bronwen":"Bronwen","elizabeth":"elizabeth","judith":"Judith","paul":"Paul","witch":"Witch"},
  12. "us" : {"bruce":"Bruce","jenny":"Jenny"},
  13. "es" : {"martha":"Martha"},
  14. "it" : {"sonia":"Sonia"}
  15. }
  16. CACHE_PATH = "/tmp/jarvis/tts/acapela/"
  17. def say(words=None, voice=None, language=None, cache=None):
  18. if not os.path.exists(CACHE_PATH):
  19. os.makedirs(CACHE_PATH)
  20. sha1 = sha.new(words).hexdigest()
  21. tempfile = CACHE_PATH+voice+"."+sha1+".tts"
  22. get_audio(voice,words,tempfile,cache)
  23. play_audio(tempfile)
  24. if not cache:
  25. os.remove(tempfile)
  26. def get_audio(voice, text, filepath,cache):
  27. if not cache or not os.path.exists(filepath):
  28. payload ={
  29. "method" : "redirect",
  30. "text" : text.encode('utf8'),
  31. "voice" : voice
  32. }
  33. r = requests.get("http://www.acapela-group.com/demo-tts/DemoHTML5Form_V2_fr.php", params=payload, stream=True)
  34. logging.debug("Trying to get url: %s response code: %s",r.url,r.status_code)
  35. if r.status_code==200:
  36. with open(os.path.abspath(filepath), "wb") as sound_file:
  37. sound_file.write(r.content)
  38. def play_audio(music_file, volume=0.8):
  39. pygame.mixer.init(16000, -16, 1, 2048)
  40. pygame.mixer.music.set_volume(volume)
  41. clock = pygame.time.Clock()
  42. try:
  43. pygame.mixer.music.load(music_file)
  44. logging.debug("Music file {} loaded!".format(music_file))
  45. except pygame.error:
  46. os.remove(music_file)
  47. logging.debug("File {} not found! ({})".format(music_file, pygame.get_error()))
  48. return
  49. pygame.mixer.music.play()
  50. while pygame.mixer.music.get_busy():
  51. clock.tick(10)
  52. def get_voice(voice=None, language=None):
  53. if language in VOXYGEN_LANGUAGES:
  54. if voice in VOXYGEN_LANGUAGES[language]:
  55. return VOXYGEN_LANGUAGES[language][voice]
  56. logging.debug("Cannot find language maching language: %s voice: %s",language,voice)
  57. return ""
  58. def wipe_cache():
  59. shutil.rmtree(CACHE_PATH)
  60. import sys
  61. logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
  62. say("Bonjour monsieur",get_voice("loic","fr"),None,True)