1 | import os
|
---|
2 | import sys
|
---|
3 |
|
---|
4 | import pygame
|
---|
5 |
|
---|
6 | import data
|
---|
7 | from config import config
|
---|
8 | import constants
|
---|
9 |
|
---|
10 | SOUND_INITIALIZED = False
|
---|
11 |
|
---|
12 | def 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 |
|
---|
23 | SOUND_CACHE = {}
|
---|
24 |
|
---|
25 | def 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 |
|
---|
37 | CURRENT_MUSIC_FILE = None
|
---|
38 |
|
---|
39 | def 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 |
|
---|
48 | def 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 |
|
---|