| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- import os
- import time
- import wave
- import pyaudio
- _CLIP_FOLDER = os.path.join('resources', 'clips')
- _CLIP_DATA_CACHE = {}
- class Clips(object):
- SUCCESS = 'ding.wav'
- FAILURE = 'dong.wav'
- DING = 'ding.wav'
- DONG = 'dong.wav'
- def play(clip):
- """Simple callback function to play a wave file. By default it plays
- a Ding sound.
- :param str fname: wave file name
- :return: None
- """
- audio = pyaudio.PyAudio()
- if clip not in _CLIP_DATA_CACHE:
- fname = os.path.join(_CLIP_FOLDER, clip)
- f = wave.open(fname, 'rb')
- data = f.readframes(f.getnframes())
- n_channels = f.getnchannels()
- width = f.getsampwidth()
- framerate = f.getframerate()
- _CLIP_DATA_CACHE[clip] = (data, n_channels, width, framerate)
- data, n_channels, width, framerate = _CLIP_DATA_CACHE[clip]
- audio = pyaudio.PyAudio()
- stream_out = audio.open(
- format=audio.get_format_from_width(width),
- channels=n_channels,
- rate=framerate, input=False, output=True)
- stream_out.start_stream()
- stream_out.write(data)
- time.sleep(0.2)
- stream_out.stop_stream()
- stream_out.close()
- audio.terminate()
|