Repository navigation
Expand file tree
/
Copy pathSoundControl.py
More file actions
executable file
·216 lines (182 loc) · 7.55 KB
/
Copy pathSoundControl.py
File metadata and controls
executable file
·216 lines (182 loc) · 7.55 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import datetime
import json
import os.path
import asyncio
import pygame
from threading import Timer
import time
import sys
from settings import timerDurations, configFolder, audioFolder, blipFile, readyFile, audioFeedbackVolume
import glob
from tinytag import TinyTag
mixer = pygame.mixer.init()
print("Mixer status: ", mixer)
# Makes sure Volume is within appropriate levels
def clampVolume(n, min_value, max_value):
return max(min_value,min(int(n),max_value))
# Returns the closest number from a list
def closest(list, k):
return list[min(range(len(list)), key = lambda i: abs(list[i]-k))]
class FancyTimer(Timer):
started_at = None
def start(self):
self.started_at = time.time()
Timer.start(self)
def elapsed(self):
return time.time() - self.started_at
def remaining(self):
return max(self.interval - self.elapsed(),0)
class SoundControl:
def getVolume(self):
with open(os.path.join(configFolder, "volume.json")) as f:
volume = json.load(f)
return volume['level']
def setVolume(self,new_volume):
with open(os.path.join(configFolder, "volume.json"),'r+') as f:
read_volume = json.load(f)
if str(new_volume)[0] == "+":
new_volume = clampVolume(read_volume['level'] + int(str(new_volume)[1:]),self.min_volume,self.max_volume)
elif str(new_volume)[0] == "-":
new_volume = clampVolume(read_volume['level'] - int(str(new_volume)[1:]),self.min_volume,self.max_volume)
else:
new_volume = clampVolume(new_volume,self.min_volume,self.max_volume)
# change the volume!
pygame.mixer.music.set_volume(new_volume/100)
# write to the file
print("Volume was {0} and is now {1}. (JSON: {2})".format(read_volume['level'],new_volume,read_volume))
read_volume['level'] = new_volume
self.writeVolume(new_volume,f)
return new_volume
def writeVolume(self,new_volume:int,file=False):
if file:
try:
file.truncate(0)
file.seek(0)
json.dump({"level":new_volume},file)
except:
print("Could not write the Volume to disk.")
else:
print("writeVolume requires a file")
def getTracks(self):
# because glob is not case-insensitive!
projectFiles = glob.glob(audioFolder + '*.[mM][pP]3') + glob.glob(audioFolder + '*.[wW][aA][vV]')
tracks = []
for file in projectFiles:
audiofile = TinyTag.get(file)
if (audiofile.title is None):
title = os.path.splitext(file)[0].split("/")[-1].capitalize()
else:
title = audiofile.title
tracks.append({"filename":file.split("/")[-1],"title":title})
return tracks
def getTrack(self):
with open(os.path.join(configFolder, "track.json")) as f:
track = json.load(f)
return track['filename']
def getTrackTitle(self):
filepath = audioFolder + self.getTrack()
audiofile = TinyTag.get(filepath)
if (audiofile.title is None):
return os.path.splitext(filepath)[0].split("/")[-1].capitalize()
else:
return audiofile.title
def setTrack(self, new_track):
with open(os.path.join(configFolder, "track.json"),'r+') as f:
read_track = json.load(f)
read_track['filename'] = new_track
f.seek(0)
f.write(json.dumps(read_track))
f.truncate()
# check to see if something is playing,
# if so, check the timer, change the track, then start playing again
print("Now we will change the soundz")
if pygame.mixer.music.get_busy() == True:
pygame.mixer.music.stop()
pygame.mixer.music.load(os.path.join(audioFolder,new_track))
pygame.mixer.music.play(loops=-1) #-1 loops = infinite
r = self.countdown.remaining()
self.countdown.cancel()
self.countdown = FancyTimer(r, self.stopTrack)
self.countdown.start()
return new_track
def startTrack(self):
track_filename = self.getTrack()
if pygame.mixer.music.get_busy() == False:
pygame.mixer.music.load(os.path.join(audioFolder,track_filename))
pygame.mixer.music.play(loops=-1) #-1 loops = infinite
def stopTrack(self):
pygame.mixer.music.stop()
# Cannot use pygame.mixer.music.fadeout(5000) to fadeout because
# it is blocking. So you will need to write a custom fadeout function
if self.countdown != False:
self.countdown.cancel()
self.countdown = False
self.writeTimer(0)
self.blip()
def getTimer(self):
with open(os.path.join(configFolder, "timer.json")) as f:
timer = json.load(f)
return timer['duration']
# set a new timer or bop through the available timer settings
def setTimer(self, input_time:int=-1):
with open(os.path.join(configFolder, "timer.json"),'r+') as f:
read_timer = json.load(f)
print("input time:",input_time)
if (int(input_time) > -1):
new_timer = int(input_time)
else:
c = closest(self.timerDurations,read_timer['duration'])
c = self.timerDurations.index(c)+1
new_timer = self.timerDurations[c] if c < len(self.timerDurations) else self.timerDurations[0]
print("Timer was {0} and is now {1}.".format(read_timer['duration'],new_timer))
read_timer['duration'] = new_timer
# now write the new timer
self.writeTimer(new_timer,f)
if (new_timer > 0):
self.startTrack()
if self.countdown != False: self.countdown.cancel()
self.countdown = FancyTimer(new_timer, self.stopTrack)
self.countdown.start()
else:
self.stopTrack()
return new_timer
def writeTimer(self,new_time:int,file=False):
if file:
try:
file.truncate(0)
file.seek(0)
json.dump({"duration":new_time},file)
except:
print("Could not write the Timer to disk.")
else:
try:
with open(os.path.join(configFolder, "timer.json"),'w') as f:
json.dump({"duration":0},f)
except:
print("Could not write the Timer to disk.")
def timerRemaining(self):
if self.countdown is False:
return 0
else:
return self.countdown.remaining()
def blip(self):
self.audioFeedback(blipFile)
def ready(self):
self.audioFeedback(readyFile)
def audioFeedback(self,audioFile):
beforeVolume = self.getVolume()
self.setVolume(audioFeedbackVolume)
pygame.mixer.music.load(audioFile)
pygame.mixer.music.play(1) #-1 loops = infinite
self.setVolume(beforeVolume)
def __init__(self, volume:int=50, timer:int=60, track="pianoloop.mp3"):
self.min_volume = 0
self.max_volume = 100
self.volume = self.getVolume()
self.track = self.getTrack()
self.timerDurations = timerDurations
self.timer = self.getTimer()
self.countdown = False
# set the timer up so it's begins at the right place since
# we're turning on for the first time
self.writeTimer(self,0)