changeset 90:23a8b2e49e9f

Added ability to initialize sound and play sounds, and handle sound not working / file being missing etc
author David Fraser <davidf@sjsoft.com>
date Wed, 02 Sep 2009 10:34:22 +0000
parents c0455e6c99f4
children db78e8b1f8b0
files gamelib/constants.py gamelib/main.py gamelib/sound.py
diffstat 3 files changed, 37 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/gamelib/constants.py	Wed Sep 02 10:33:35 2009 +0000
+++ b/gamelib/constants.py	Wed Sep 02 10:34:22 2009 +0000
@@ -17,6 +17,13 @@
 FG_COLOR = (255, 255, 255)
 BG_COLOR = (0, 0, 0)
 
+# Mixer constants
+FREQ = 44100   # same as audio CD
+BITSIZE = -16  # unsigned 16 bit
+CHANNELS = 2   # 1 == mono, 2 == stereo
+BUFFER = 1024  # audio buffer size in no. of samples
+FRAMERATE = 30 # how often to check if playback has finished
+
 # Game constants
 
 STARTING_CASH = 1000
--- a/gamelib/main.py	Wed Sep 02 10:33:35 2009 +0000
+++ b/gamelib/main.py	Wed Sep 02 10:34:22 2009 +0000
@@ -12,6 +12,7 @@
 
 from mainmenu import MainMenu
 from engine import Engine, MainMenuState
+from sound import init_sound
 import constants
 
 def create_menu_app():
@@ -27,6 +28,7 @@
 
 def main():
     """Main script."""
+    init_sound()
     screen = pygame.display.set_mode(constants.SCREEN, SWSURFACE)
     main_menu_app = create_menu_app()
     engine = Engine(main_menu_app)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gamelib/sound.py	Wed Sep 02 10:34:22 2009 +0000
@@ -0,0 +1,28 @@
+import os
+import pygame
+
+import data
+import constants
+
+SOUND_INITIALIZED = False
+
+def init_sound():
+    """initialize the sound system"""
+    global SOUND_INITIALIZED
+    try:
+        pygame.mixer.init(constants.FREQ, constants.BITSIZE, constants.CHANNELS, constants.BUFFER)
+        SOUND_INITIALIZED = True
+    except pygame.error, exc:
+        print >>sys.stderr, "Could not initialize sound system: %s" % exc
+
+def play_sound(filename):
+    """plays the sound with the given filename from the data sounds directory"""
+    if not SOUND_INITIALIZED:
+        return
+    file_path = data.filepath("sounds", filename)
+    if not os.path.exists(file_path):
+        return
+    pygame.mixer.music.load(file_path)
+    pygame.mixer.music.play()
+
+