view 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
line wrap: on
line source

"""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, volume=1.0):
        if self.sound_enabled:
            try:
                mixer.music.load(data.filepath(track_name))
                mixer.music.play(-1)  # Loop forever
                mixer.music.set_volume(volume)
            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.mixer.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()