source: skaapsteker/sound.py

Last change on this file was 553:62569f486ede, checked in by Jeremy Thurgood <firxen@…>, 12 years ago

Debug print cleanup.

File size: 2.2 KB
Line 
1"""Support for playing sounds and music"""
2
3from pygame import mixer
4import pygame
5from . import data
6from .constants import FREQ, BITSIZE, CHANNELS, BUFFER
7
8_GLOBAL_SOUND = None
9
10
11def load_sound(key, track_name, volume=None):
12 if _GLOBAL_SOUND is not None:
13 _GLOBAL_SOUND.load_sound(key, track_name, volume)
14
15def play_sound(key):
16 if _GLOBAL_SOUND is not None:
17 _GLOBAL_SOUND.play_sound(key)
18
19
20class SoundSystem(object):
21
22 def __init__(self, want_sound):
23 global _GLOBAL_SOUND
24 if want_sound:
25 # See if we can actually enabled sound
26 try:
27 mixer.init(FREQ, BITSIZE, CHANNELS, BUFFER)
28 test_sound = mixer.Sound(data.filepath('sounds/silence.ogg'))
29 test_sound.play()
30 self.sound_enabled = True
31 except pygame.error:
32 print 'Unable to enable sound'
33 self.sound_enabled = False
34 else:
35 self.sound_enabled = False
36
37 self._sounds = {}
38 _GLOBAL_SOUND = self
39
40
41 def play_background_music(self, track_name, volume=1.0):
42 if self.sound_enabled:
43 try:
44 mixer.music.load(data.filepath(track_name))
45 mixer.music.play(-1) # Loop forever
46 mixer.music.set_volume(volume)
47 except pygame.error:
48 print 'Unable to load track'
49
50 def stop_music(self):
51 if self.sound_enabled:
52 mixer.music.stop()
53
54 def load_sound(self, key, track_name, volume=None):
55 if key in self._sounds:
56 # First caller wins on duplicate keys
57 return
58 if not self.sound_enabled:
59 self._sounds[key] = None
60 else:
61 self._sounds[key] = pygame.mixer.Sound(data.filepath(track_name))
62 if volume is not None:
63 self._sounds[key].set_volume(volume)
64
65 def play_sound(self, key):
66 sound = self._sounds.get(key, None)
67 if sound:
68 sound.play()
69
70 def stop_all_sounds(self):
71 if self.sound_enabled:
72 mixer.stop()
73
74 def pause(self):
75 if self.sound_enabled:
76 mixer.music.pause()
77
78 def unpause(self):
79 if self.sound_enabled:
80 mixer.music.unpause()
Note: See TracBrowser for help on using the repository browser.