source: nagslang/sound.py@ 689:45d2a6aef3a4

Last change on this file since 689:45d2a6aef3a4 was 689:45d2a6aef3a4, checked in by Neil Muller <drnlmuller@…>, 2 years ago

Some flake8 fixes

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