-
Notifications
You must be signed in to change notification settings - Fork 0
/
audiolib.py
44 lines (39 loc) · 1.22 KB
/
audiolib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import pyaudio
import wave
from utils import resource_path
import sys
class AudioFile(object):
chunk = 1024
def __init__(self, file=None, file_data=None):
""" Init audio stream """
if file:
self.wf = wave.open(file, 'rb')
else:
self.wf = wave.open(file_data, 'rb')
self.p = pyaudio.PyAudio()
self.stream = self.p.open(
format=self.p.get_format_from_width(self.wf.getsampwidth()),
channels=self.wf.getnchannels(),
rate=self.wf.getframerate(),
output=True
)
def play(self):
""" Play entire file """
data = self.wf.readframes(self.chunk)
while data:
self.stream.write(data)
data = self.wf.readframes(self.chunk)
def close(self):
""" Gracefully close the file """
self.stream.stop_stream()
self.stream.close()
self.p.terminate()
if __name__ == '__main__':
if len(sys.argv) >= 2:
audio_file = AudioFile(file=resource_path(sys.argv[1]))
audio_file.play()
audio_file.close()
else:
audio_file = AudioFile(file=resource_path('assets/beep.wav'))
audio_file.play()
audio_file.close()