-
Notifications
You must be signed in to change notification settings - Fork 0
/
track.py
58 lines (43 loc) · 1.4 KB
/
track.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import os
import wave
import threading # for looping tracks
import sys
import pyaudio # to play the looped tracks
import simpleaudio as sa # to play simple tracks -> should maybe move all to pyaudio?
# helper function
def play_wav(name):
''' Play audio file name and return its playing object'''
w = sa.WaveObject.from_wave_file(name)
pl = w.play()
# will make the code wait rathe than execute the lines below
# pl.wait_done()
return pl
class Track(threading.Thread):
'''
looped track
'''
def __init__(self, filepath) :
super(Track, self).__init__()
self.filepath = filepath
self.loop = True # when set false, the track will stop playing
self.chunk = 1024
def run(self):
''' overridden '''
# start playing
wf = wave.open(self.filepath, 'rb')
pl = pyaudio.PyAudio()
# Open Output Stream (basen on PyAudio tutorial)
stream = pl.open(format = pl.get_format_from_width(wf.getsampwidth()),
channels = wf.getnchannels(),
rate = wf.getframerate(),
output = True)
# PLAYBACK LOOP
while self.loop:
data = wf.readframes(self.chunk)
stream.write(data)
if data == b'' : # If file is over then rewind.
wf.rewind()
stream.close()
pl.terminate()
def stop(self):
self.loop = False