source: nagslang/sound.py@ 269:9fcdb106424a

Last change on this file since 269:9fcdb106424a was 269:9fcdb106424a, checked in by Simon Cross <hodgestar@…>, 8 years ago

Add first draft of sound support.

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 track_name = resources.get_resource_path("music", name)
53 mixer.music.load(track_name)
54 mixer.music.set_volume(volume)
55 mixer.music.play(-1) # loop sound
56
57 def pause_music(self):
58 mixer.music.pause()
59
60 def unpause_music(self):
61 mixer.music.unpause()
62
63 def stop(self):
64 mixer.stop()
65 mixer.music.stop()
66
67
68class SoundProxy(object):
69 def __init__(self):
70 self._sound = DummySound()
71
72 def init(self):
73 """Attempt to initialize the sound system."""
74 if options.sound:
75 try:
76 pyg_sound = PygameSound()
77 pyg_sound.init()
78 self._sound = pyg_sound
79 except Exception, err:
80 print "Failed to enable sound: %r" % (err,)
81
82 def __getattr__(self, name):
83 return getattr(self._sound, name)
84
85
86sound = SoundProxy()
Note: See TracBrowser for help on using the repository browser.