changeset 501:4778c482f24a

Make SDL(sound=False) work again, and disable sound if an exception occurs while setting it up.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Wed, 23 Oct 2013 18:24:07 +0200
parents 777544d11578
children 3d3285918ba1
files pytouhou/lib/sdl.pyx pytouhou/ui/music.pyx
diffstat 2 files changed, 24 insertions(+), 5 deletions(-) [+]
line wrap: on
line diff
--- a/pytouhou/lib/sdl.pyx
+++ b/pytouhou/lib/sdl.pyx
@@ -12,6 +12,11 @@
 ## GNU General Public License for more details.
 ##
 
+from pytouhou.utils.helpers import get_logger
+
+logger = get_logger(__name__)
+
+
 GL_CONTEXT_MAJOR_VERSION = SDL_GL_CONTEXT_MAJOR_VERSION
 GL_CONTEXT_MINOR_VERSION = SDL_GL_CONTEXT_MINOR_VERSION
 GL_DOUBLEBUFFER = SDL_GL_DOUBLEBUFFER
@@ -56,8 +61,13 @@ class SDL(object):
 
         if self.sound:
             mix_init(0)
-            mix_open_audio(44100, MIX_DEFAULT_FORMAT, 2, 4096)
-            mix_allocate_channels(MAX_CHANNELS) #TODO: make it dependent on the SFX number.
+            try:
+                mix_open_audio(44100, MIX_DEFAULT_FORMAT, 2, 4096)
+            except SDLError as error:
+                logger.error(u'Impossible to set up audio subsystem: %s', error)
+                self.sound = False
+            else:
+                mix_allocate_channels(MAX_CHANNELS) #TODO: make it dependent on the SFX number.
 
     def __exit__(self, *args):
         if self.sound:
--- a/pytouhou/ui/music.pyx
+++ b/pytouhou/ui/music.pyx
@@ -15,6 +15,7 @@
 
 from os.path import join
 from glob import glob
+from pytouhou.lib import sdl
 from pytouhou.lib cimport sdl
 from pytouhou.utils.helpers import get_logger
 
@@ -55,7 +56,7 @@ class MusicPlayer(object):
     def play(self, index):
         cdef sdl.Music bgm
         bgm = self.bgms[index]
-        if bgm:
+        if bgm is not None:
             bgm.play(-1)
 
 
@@ -74,16 +75,24 @@ class SFXPlayer(object):
         return self.channels[name]
 
     def get_sound(self, name):
+        cdef sdl.Chunk chunk
         if name not in self.sounds:
             wave_file = self.loader.get_file(name)
-            chunk = sdl.load_chunk(wave_file)
-            chunk.set_volume(self.volume)
+            try:
+                chunk = sdl.load_chunk(wave_file)
+            except sdl.SDLError as error:
+                logger.warn(u'Sound ā€œ%sā€ not found: %s', name, error)
+                chunk = None
+            else:
+                chunk.set_volume(self.volume)
             self.sounds[name] = chunk
         return self.sounds[name]
 
     def play(self, name, volume=None):
         cdef sdl.Chunk sound
         sound = self.get_sound(name)
+        if sound is None:
+            return
         channel = self.get_channel(name)
         if volume:
             sdl.mix_volume(channel, volume)