source: gamelib/sound.py@ 411:03d5cb669298

Last change on this file since 411:03d5cb669298 was 411:03d5cb669298, checked in by Jeremy Thurgood <firxen@…>, 11 years ago

Add config file and command line parameters.

File size: 1.8 KB
Line 
1import os
2import sys
3
4import pygame
5
6import data
7from config import config
8import constants
9
10SOUND_INITIALIZED = False
11
12def init_sound():
13 """initialize the sound system"""
14 global SOUND_INITIALIZED
15 if not config.sound:
16 return
17 try:
18 pygame.mixer.init(constants.FREQ, constants.BITSIZE, constants.CHANNELS, constants.BUFFER)
19 SOUND_INITIALIZED = True
20 except pygame.error, exc:
21 print >>sys.stderr, "Could not initialize sound system: %s" % exc
22
23SOUND_CACHE = {}
24
25def play_sound(filename):
26 """plays the sound with the given filename from the data sounds directory"""
27 if not (SOUND_INITIALIZED and config.sound):
28 return
29 file_path = data.filepath("sounds", filename)
30 sound = SOUND_CACHE.get(file_path, None)
31 if not sound:
32 if not os.path.exists(file_path):
33 return
34 SOUND_CACHE[file_path] = sound = pygame.mixer.Sound(file_path)
35 sound.play()
36
37CURRENT_MUSIC_FILE = None
38
39def stop_background_music():
40 """stops any playing background music"""
41 global CURRENT_MUSIC_FILE
42 if not (SOUND_INITIALIZED and config.sound):
43 return
44 CURRENT_MUSIC_FILE = None
45 # TODO: fadeout in a background thread
46 pygame.mixer.music.stop()
47
48def background_music(filename):
49 """plays the background music with the given filename from the data sounds directory"""
50 global CURRENT_MUSIC_FILE
51 if not (SOUND_INITIALIZED and config.sound):
52 return
53 file_path = data.filepath("sounds", filename)
54 if CURRENT_MUSIC_FILE == file_path:
55 return
56 stop_background_music()
57 if not os.path.exists(file_path):
58 return
59 CURRENT_MUSIC_FILE = file_path
60 pygame.mixer.music.load(file_path)
61 pygame.mixer.music.set_volume(0.3)
62 pygame.mixer.music.play(-1)
63
Note: See TracBrowser for help on using the repository browser.