clips.py 1.2 KB

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