1 | import os
|
---|
2 | import pygame
|
---|
3 | import sys
|
---|
4 |
|
---|
5 | import data
|
---|
6 | import constants
|
---|
7 |
|
---|
8 | SOUND_INITIALIZED = False
|
---|
9 |
|
---|
10 | def 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 |
|
---|
19 | SOUND_CACHE = {}
|
---|
20 |
|
---|
21 | def 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 |
|
---|
33 | CURRENT_MUSIC_FILE = None
|
---|
34 |
|
---|
35 | def 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 |
|
---|
44 | def 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 |
|
---|