pgfw/pgfw/Audio.py

75 lines
2.4 KiB
Python

from os import listdir
from os.path import join
from pygame.mixer import Channel, Sound, music, find_channel, get_num_channels
from GameChild import *
from Input import *
class Audio(GameChild):
UP, DOWN = .1, -.1
BASE_VOLUME = .8
def __init__(self, game):
GameChild.__init__(self, game)
self.original_volumes = {}
self.volume = self.BASE_VOLUME
if self.check_command_line("-mute"):
self.volume = 0
self.subscribe(self.respond)
def set_volume(self, volume=None, increment=None, mute=False):
if mute:
self.volume = 0
elif increment:
self.volume += increment
if self.volume > 1:
self.volume = 1.0
elif self.volume < 0:
self.volume = 0
else:
self.volume = volume
def respond(self, event):
compare = self.get_game().delegate.compare
if compare(event, "volume-mute"):
self.set_volume(mute=True)
elif compare(event, "volume-up"):
self.set_volume(increment=self.UP)
elif compare(event, "volume-down"):
self.set_volume(increment=self.DOWN)
def update(self):
for ii in xrange(get_num_channels()):
channel = Channel(ii)
sound = channel.get_sound()
if sound is not None:
if sound not in self.original_volumes.keys():
self.original_volumes[sound] = sound.get_volume()
sound.set_volume(self.original_volumes[sound] * self.volume)
class SoundEffect(GameChild, Sound):
def __init__(self, parent, path, volume=1.0):
GameChild.__init__(self, parent)
Sound.__init__(self, path)
self.display_surface = self.get_display_surface()
self.initial_volume = volume
self.set_volume(volume)
def play(self, loops=0, maxtime=0, fade_ms=0, position=None, x=None):
self.set_volume(self.initial_volume *
self.get_configuration("audio", "sfx-volume"))
channel = Sound.play(self, loops, maxtime, fade_ms)
if x is not None:
position = float(x) / self.display_surface.get_width()
if position is not None and channel is not None:
channel.set_volume(*self.get_panning(position))
return channel
def get_panning(self, position):
return 1 - max(0, ((position - .5) * 2)), \
1 + min(0, ((position - .5) * 2))