audio_output.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import os
  2. import time
  3. import hashlib
  4. import pyaudio
  5. from gtts import gTTS
  6. import pygame.mixer
  7. import base
  8. from voice_control.conf import CLIPS_FOLDER
  9. _CLIP_DATA_CACHE = {}
  10. if not os.path.isdir('/tmp/snowboy'):
  11. os.mkdir('/tmp/snowboy')
  12. TMP_DIR = '/tmp/snowboy/tts-cache'
  13. if not os.path.isdir(TMP_DIR):
  14. os.mkdir(TMP_DIR)
  15. class Clips(object):
  16. SUCCESS = 'ding.wav'
  17. FAILURE = 'dong.wav'
  18. DING = 'ding.wav'
  19. DONG = 'dong.wav'
  20. def _play(fname, block):
  21. pygame.mixer.init()
  22. pygame.mixer.music.load(fname)
  23. pygame.mixer.music.play()
  24. if block:
  25. while pygame.mixer.music.get_busy():
  26. time.sleep(0.1)
  27. def _play_clip(clip):
  28. """Simple callback function to play a wave file. By default it plays
  29. a Ding sound.
  30. :param str fname: wave file name
  31. :return: None
  32. """
  33. fname = os.path.join(CLIPS_FOLDER, clip)
  34. _play(fname, True)
  35. return
  36. class AudioOutput(base.Base):
  37. def tts(self, text):
  38. if not text:
  39. return
  40. tts_hash = hashlib.md5(text.lower()).hexdigest()
  41. cache_fname = os.path.join(TMP_DIR, tts_hash) + '.mp3'
  42. if os.path.isfile(cache_fname):
  43. _play(cache_fname, True)
  44. return
  45. tts_stream = gTTS(text=text, lang='en')
  46. with open(cache_fname, 'w') as f:
  47. tts_stream.write_to_fp(f)
  48. _play(cache_fname, True)
  49. def success(self):
  50. _play_clip(Clips.SUCCESS)
  51. def failure(self, *_):
  52. _play_clip(Clips.FAILURE)
  53. def cancelled(self):
  54. self.tts('cancelled')