Mercurial > skaapsteker
diff skaapsteker/sound.py @ 262:de60329cfc9f
Factor out sound stuff
author | Neil Muller <drnlmuller@gmail.com> |
---|---|
date | Fri, 08 Apr 2011 11:29:37 +0200 |
parents | |
children | 44cd7cfd2de3 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/skaapsteker/sound.py Fri Apr 08 11:29:37 2011 +0200 @@ -0,0 +1,56 @@ +"""Support for playing sounds and music""" + +from pygame import mixer +import pygame +from . import data +from .constants import FREQ, BITSIZE, CHANNELS, BUFFER + +class SoundSystem(object): + + def __init__(self, want_sound): + if want_sound: + # See if we can actually enabled sound + try: + mixer.init(FREQ, BITSIZE, CHANNELS, BUFFER) + test_sound = mixer.Sound(data.filepath('sounds/silence.ogg')) + test_sound.play() + self.sound_enabled = True + except pygame.error: + print 'Unable to enable sound' + self.sound_enabled = False + else: + self.sound_enabled = False + + self._sounds = {} + + + def play_background_music(self, track_name): + if self.sound_enabled: + try: + mixer.music.load(data.filepath(track_name)) + mixer.music.play(-1) # Loop forever + except pygame.error: + print 'Unable to load track' + + def stop_music(self): + if self.sound_enabled: + mixer.music.stop() + + def load_sound(self, key, track_name): + if key in self._sounds: + # First caller wins on duplicate keys + return + if not self.sound_enabled: + self._sounds[key] = None + else: + self._sounds[key] = pygame.sound.Sound(data.filepath(track_name)) + + def play_sound(self, key): + sound = self._sounds.get(key, None) + if sound: + sound.play() + + def stop_all_sounds(self): + if self.sound_enabled: + mixer.stop() +