source: nagslang/sound.py @ 598:e65d59081bdd

Last change on this file since 598:e65d59081bdd was 598:e65d59081bdd, checked in by Simon Cross <hodgestar@…>, 7 years ago

Quieter sound.

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