-
Notifications
You must be signed in to change notification settings - Fork 0
/
sound.py
62 lines (50 loc) · 1.53 KB
/
sound.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
59
60
61
62
from pygame import mixer
import math
def init_sound():
mixer.init(channels=2)
mixer.set_num_channels(11)
def playSfx(track, channel=1, volume=1, loops=0):
# failsafe
if channel == 0:
print("WARNING: Channel 0 is reserved for BGM!")
# don't just quit the program due to a sound playing fail
# try to find another available channel instead
for i in range(1, 10):
if not getChannelBusy(i):
channel = i
# no available channel to fallback?
# well, we will have to interrupt one then...
if channel == 0:
channel = 1
chn = mixer.Channel(channel)
track_path = "data/sfx/" + str(track) + ".ogg"
snd = mixer.Sound(track_path)
chn.set_volume(volume)
chn.play(snd, loops)
def playBGM(track, volume=1):
chn = mixer.Channel(0)
track_path = track
snd = mixer.Sound(track_path)
chn.set_volume(volume)
chn.play(snd, -1)
def stopChannel(channel):
try:
chn = mixer.Channel(channel)
chn.stop()
except IndexError:
pass
def getChannelBusy(channel):
try:
chn = mixer.Channel(channel)
return chn.get_busy()
except IndexError:
return False
def getVolumeAtDistance(dist):
return min(1, 1/(dist**2))
def setChannelVolume(channel, volume_left, volume_right = None):
chn = mixer.Channel(channel)
if not volume_right:
chn.set_volume(volume_left)
else:
# yeah, can also do panning!
chn.set_volume(volume_left, volume_right)