93 lines
2.4 KiB
Python
93 lines
2.4 KiB
Python
from os import listdir
|
|
from os.path import join
|
|
|
|
from pygame.mixer import Channel, Sound, music, find_channel
|
|
|
|
from GameChild import *
|
|
from Input import *
|
|
|
|
class Audio(GameChild):
|
|
|
|
current_channel = None
|
|
paused = False
|
|
muted = False
|
|
|
|
def __init__(self, game):
|
|
GameChild.__init__(self, game)
|
|
self.delegate = self.get_delegate()
|
|
self.load_fx()
|
|
self.subscribe(self.respond)
|
|
|
|
def load_fx(self):
|
|
fx = {}
|
|
if self.get_configuration().has_option("audio", "sfx-path"):
|
|
root = self.get_resource("audio", "sfx-path")
|
|
if root:
|
|
for name in listdir(root):
|
|
fx[name.split(".")[0]] = Sound(join(root, name))
|
|
self.fx = fx
|
|
|
|
def respond(self, event):
|
|
if self.delegate.compare(event, "mute"):
|
|
self.mute()
|
|
|
|
def mute(self):
|
|
self.muted = True
|
|
self.set_volume()
|
|
|
|
def unmute(self):
|
|
self.muted = False
|
|
self.set_volume()
|
|
|
|
def set_volume(self):
|
|
volume = int(not self.muted)
|
|
music.set_volume(volume)
|
|
if self.current_channel:
|
|
self.current_channel.set_volume(volume)
|
|
|
|
def play_bgm(self, path, stream=False):
|
|
self.stop_current_channel()
|
|
if stream:
|
|
music.load(path)
|
|
music.play(-1)
|
|
else:
|
|
self.current_channel = Sound(path).play(-1)
|
|
self.set_volume()
|
|
|
|
def stop_current_channel(self):
|
|
music.stop()
|
|
if self.current_channel:
|
|
self.current_channel.stop()
|
|
self.current_channel = None
|
|
self.paused = False
|
|
|
|
def play_fx(self, name, panning=.5):
|
|
if not self.muted:
|
|
channel = find_channel(True)
|
|
if panning != .5:
|
|
offset = 1 - abs(panning - .5) * 2
|
|
if panning < .5:
|
|
channel.set_volume(1, offset)
|
|
else:
|
|
channel.set_volume(offset, 1)
|
|
channel.play(self.fx[name])
|
|
|
|
def pause(self):
|
|
channel = self.current_channel
|
|
paused = self.paused
|
|
if paused:
|
|
music.unpause()
|
|
if channel:
|
|
channel.unpause()
|
|
else:
|
|
music.pause()
|
|
if channel:
|
|
channel.pause()
|
|
self.paused = not paused
|
|
|
|
def is_bgm_playing(self):
|
|
current = self.current_channel
|
|
if current and current.get_sound():
|
|
return True
|
|
return music.get_busy()
|