1 /*
2 * sound with SDL_mixer.dll (not changing the volume of other programs)
3 *
4 * This file is part of the Simutrans project under the artistic license.
5 */
6
7 #include <SDL.h>
8 #include <SDL_mixer.h>
9 #include <string.h>
10 #include "sound.h"
11 #include "../simdebug.h"
12
13
14 /*
15 * Hajo: flag if sound module should be used
16 */
17 static int use_sound = 0;
18
19 /* this list contains all the samples
20 */
21 static Mix_Chunk *samples[64];
22
23 /* all samples are stored chronologically there
24 */
25 static int samplenumber = 0;
26
27
28 /**
29 * Sound initialisation routine
30 */
dr_init_sound()31 bool dr_init_sound()
32 {
33 int sound_ok = 0;
34 if(use_sound!=0) {
35 return true; // avoid init twice
36 }
37 use_sound = 1;
38
39 // initialize SDL sound subsystem
40 if (SDL_InitSubSystem(SDL_INIT_AUDIO) != -1) {
41
42 // open an audio channel
43
44 int freq = 22050;
45 int channels = 1;
46 unsigned short int format = AUDIO_S16SYS;
47 int samples = 1024;
48
49 if (Mix_OpenAudio(freq, format, channels, samples) != -1) {
50 Mix_QuerySpec(&freq, &format, &channels);
51 // check if we got the right audio format
52 if (format == AUDIO_S16SYS) {
53 // finished initializing
54 sound_ok = 1;
55
56 // allocate 16 mixing channels
57 Mix_AllocateChannels(16);
58
59 // start playing sounds
60 Mix_ResumeMusic();
61
62 }
63 else {
64 dbg->error("dr_init_sound()","Open audio channel doesn't meet requirements. Muting");
65 Mix_CloseAudio();
66 SDL_QuitSubSystem(SDL_INIT_AUDIO);
67 }
68
69
70 }
71 else {
72 dbg->error("dr_init_sound()","Could not open required audio channel. Muting");
73 SDL_QuitSubSystem(SDL_INIT_AUDIO);
74 }
75 }
76 else {
77 dbg->error("dr_init_sound()","Could not initialize sound system. Muting");
78 }
79
80 use_sound = sound_ok ? 1: -1;
81 return sound_ok;
82 }
83
84
85
86 /**
87 * loads a sample
88 * @return a handle for that sample or -1 on failure
89 * @author Hj. Malthaner
90 */
dr_load_sample(const char * filename)91 int dr_load_sample(const char *filename)
92 {
93 if(use_sound>0 && samplenumber<64) {
94
95 Mix_Chunk *smp;
96
97 /* load the sample */
98 smp = Mix_LoadWAV(filename);
99 if (smp == NULL) {
100 dbg->warning("dr_load_sample()", "could not load wav (%s)", SDL_GetError());
101 return -1;
102 }
103
104 samples[samplenumber] = smp;
105 dbg->message("dr_load_sample()", "Loaded %s to sample %i.", filename, samplenumber);
106
107 return samplenumber++;
108 }
109 return -1;
110 }
111
112
113 /**
114 * plays a sample
115 * @param key the key for the sample to be played
116 * @author Hj. Malthaner
117 */
dr_play_sample(int sample_number,int volume)118 void dr_play_sample(int sample_number, int volume)
119 {
120 // sound enabled and a valid sample
121 if(use_sound>0 && sample_number != -1) {
122 // sdl_mixer finds free channel, we then play at correct volume
123 int play_channel = Mix_PlayChannel(-1, samples[sample_number], 0);
124 Mix_Volume(play_channel,(volume*MIX_MAX_VOLUME)/256);
125 }
126 }
127