source: gamelib/sound.py@ 363:e23637457aa4

Last change on this file since 363:e23637457aa4 was 363:e23637457aa4, checked in by David Fraser <davidf@…>, 11 years ago

Prevent error stopping music when sound not initialized

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