source: nagslang/sound.py@ 293:47226c661ae2

Last change on this file since 293:47226c661ae2 was 292:7b121ed73b95, checked in by Jeremy Thurgood <firxen@…>, 8 years ago

--no-music flag.

File size: 2.0 KB
Line 
1"""Sound utilities."""
2
3from pygame import mixer
4
5from nagslang.options import options
6from nagslang.resources import resources
7from nagslang.constants import FREQ, BITSIZE, CHANNELS, BUFFER
8
9
10class DummySound(object):
11 def init(self):
12 pass
13
14 def play_sound(self, name, volume=None):
15 pass
16
17 def play_music(self, name, volume=None):
18 pass
19
20 def pause_music(self):
21 pass
22
23 def resume_music(self):
24 pass
25
26 def stop(self):
27 pass
28
29
30class PygameSound(object):
31 def __init__(self):
32 self._sounds = {}
33
34 def init(self):
35 mixer.init(FREQ, BITSIZE, CHANNELS, BUFFER)
36 self.play_sound("silence.ogg")
37
38 def load_sound(self, name):
39 track_name = resources.get_resource_path("sounds", name)
40 sound = self._sounds.get(track_name)
41 if sound is None:
42 sound = self._sounds[track_name] = mixer.Sound(track_name)
43 return sound
44
45 def play_sound(self, name, volume=1.0):
46 sound = self.load_sound(name)
47 if sound is not None:
48 sound.set_volume(volume)
49 sound.play()
50
51 def play_music(self, name, volume=1.0):
52 if not options.music:
53 return
54 track_name = resources.get_resource_path("music", name)
55 mixer.music.load(track_name)
56 mixer.music.set_volume(volume)
57 mixer.music.play(-1) # loop sound
58
59 def pause_music(self):
60 mixer.music.pause()
61
62 def unpause_music(self):
63 mixer.music.unpause()
64
65 def stop(self):
66 mixer.stop()
67 mixer.music.stop()
68
69
70class SoundProxy(object):
71 def __init__(self):
72 self._sound = DummySound()
73
74 def init(self):
75 """Attempt to initialize the sound system."""
76 if options.sound:
77 try:
78 pyg_sound = PygameSound()
79 pyg_sound.init()
80 self._sound = pyg_sound
81 except Exception, err:
82 print "Failed to enable sound: %r" % (err,)
83
84 def __getattr__(self, name):
85 return getattr(self._sound, name)
86
87
88sound = SoundProxy()
Note: See TracBrowser for help on using the repository browser.