clips.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import os
  2. import time
  3. import wave
  4. import pyaudio
  5. import tts
  6. _CLIP_FOLDER = os.path.join('resources', 'clips')
  7. _CLIP_DATA_CACHE = {}
  8. class Clips(object):
  9. SUCCESS = 'ding.wav'
  10. FAILURE = 'dong.wav'
  11. DING = 'ding.wav'
  12. DONG = 'dong.wav'
  13. def play(clip):
  14. """Simple callback function to play a wave file. By default it plays
  15. a Ding sound.
  16. :param str fname: wave file name
  17. :return: None
  18. """
  19. fname = os.path.join(_CLIP_FOLDER, clip)
  20. tts._play(fname, False)
  21. return
  22. """
  23. audio = pyaudio.PyAudio()
  24. if clip not in _CLIP_DATA_CACHE:
  25. fname = os.path.join(_CLIP_FOLDER, clip)
  26. f = wave.open(fname, 'rb')
  27. data = f.readframes(f.getnframes())
  28. n_channels = f.getnchannels()
  29. width = f.getsampwidth()
  30. framerate = f.getframerate()
  31. _CLIP_DATA_CACHE[clip] = (data, n_channels, width, framerate)
  32. data, n_channels, width, framerate = _CLIP_DATA_CACHE[clip]
  33. audio = pyaudio.PyAudio()
  34. stream_out = audio.open(
  35. format=audio.get_format_from_width(width),
  36. channels=n_channels,
  37. rate=framerate, input=False, output=True)
  38. stream_out.start_stream()
  39. stream_out.write(data)
  40. time.sleep(0.2)
  41. stream_out.stop_stream()
  42. stream_out.close()
  43. audio.terminate()
  44. """