Mercurial > skaapsteker
annotate skaapsteker/sound.py @ 493:cb2060f8316f
Tweak gamestate to fail earlier on unknown items.
author | Simon Cross <hodgestar@gmail.com> |
---|---|
date | Sat, 09 Apr 2011 22:41:38 +0200 |
parents | 9c9df17b98a7 |
children | a89ab402b569 |
rev | line source |
---|---|
262 | 1 """Support for playing sounds and music""" |
2 | |
3 from pygame import mixer | |
4 import pygame | |
5 from . import data | |
6 from .constants import FREQ, BITSIZE, CHANNELS, BUFFER | |
7 | |
8 class SoundSystem(object): | |
9 | |
10 def __init__(self, want_sound): | |
11 if want_sound: | |
12 # See if we can actually enabled sound | |
13 try: | |
14 mixer.init(FREQ, BITSIZE, CHANNELS, BUFFER) | |
15 test_sound = mixer.Sound(data.filepath('sounds/silence.ogg')) | |
16 test_sound.play() | |
17 self.sound_enabled = True | |
18 except pygame.error: | |
19 print 'Unable to enable sound' | |
20 self.sound_enabled = False | |
21 else: | |
22 self.sound_enabled = False | |
23 | |
24 self._sounds = {} | |
25 | |
26 | |
453
9c9df17b98a7
Add support for choosing a volume. A music to temple.
Simon Cross <hodgestar@gmail.com>
parents:
263
diff
changeset
|
27 def play_background_music(self, track_name, volume=1.0): |
262 | 28 if self.sound_enabled: |
29 try: | |
30 mixer.music.load(data.filepath(track_name)) | |
31 mixer.music.play(-1) # Loop forever | |
453
9c9df17b98a7
Add support for choosing a volume. A music to temple.
Simon Cross <hodgestar@gmail.com>
parents:
263
diff
changeset
|
32 mixer.music.set_volume(volume) |
262 | 33 except pygame.error: |
34 print 'Unable to load track' | |
35 | |
36 def stop_music(self): | |
37 if self.sound_enabled: | |
38 mixer.music.stop() | |
39 | |
40 def load_sound(self, key, track_name): | |
41 if key in self._sounds: | |
42 # First caller wins on duplicate keys | |
43 return | |
44 if not self.sound_enabled: | |
45 self._sounds[key] = None | |
46 else: | |
263 | 47 self._sounds[key] = pygame.mixer.Sound(data.filepath(track_name)) |
262 | 48 |
49 def play_sound(self, key): | |
50 sound = self._sounds.get(key, None) | |
51 if sound: | |
52 sound.play() | |
53 | |
54 def stop_all_sounds(self): | |
55 if self.sound_enabled: | |
56 mixer.stop() | |
57 |