import os import time import logging import hashlib import pyaudio from gtts import gTTS import pygame.mixer _SOUND_ENABLED = False _CLIP_FOLDER = '/home/martin/workspaces/visual-code/voice_control/resources/clips' _CLIP_DATA_CACHE = {} if not os.path.isdir('/tmp/snowboy'): os.mkdir('/tmp/snowboy') TMP_DIR = '/tmp/snowboy/tts-cache' if not os.path.isdir(TMP_DIR): os.mkdir(TMP_DIR) class Clips(object): SUCCESS = 'ding.wav' FAILURE = 'dong.wav' DING = 'ding.wav' DONG = 'dong.wav' def _play(fname, block): pygame.mixer.init() pygame.mixer.music.load(fname) pygame.mixer.music.play() if block: while pygame.mixer.music.get_busy(): time.sleep(0.1) def tts(text, lang='en', block=True): if not text: return logging.info('> %s', text) if not _SOUND_ENABLED: return tts_hash = hashlib.md5(text.lower()).hexdigest() cache_fname = os.path.join(TMP_DIR, tts_hash) + '.mp3' if os.path.isfile(cache_fname): _play(cache_fname, block) return tts_stream = gTTS(text=text, lang=lang) with open(cache_fname, 'w') as f: tts_stream.write_to_fp(f) _play(cache_fname, block) def play_clip(clip): """Simple callback function to play a wave file. By default it plays a Ding sound. :param str fname: wave file name :return: None """ fname = os.path.join(_CLIP_FOLDER, clip) _play(fname, True) return