| 123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- import logging
- import os
- import hashlib
- import time
- from gtts import gTTS
- import pygame.mixer
- 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)
- _SOUND_ENABLED = False
- 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
- hash = hashlib.md5(text.lower()).hexdigest()
- cache_fname = os.path.join(TMP_DIR, hash) + '.mp3'
- if os.path.isfile(cache_fname):
- _play(cache_fname, block)
- return
- tts = gTTS(text=text, lang=lang)
- with open(cache_fname, 'w') as f:
- tts.write_to_fp(f)
- _play(cache_fname, block)
|