-
Notifications
You must be signed in to change notification settings - Fork 1
/
sound.cpp
70 lines (62 loc) · 1.7 KB
/
sound.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <ctime>
#include "sound.h"
using std::string;
SDLSound::~SDLSound() {
// std::cout << "Cleaning up sounds ..." << std::endl;
// std::clock_t start = std::clock();
Mix_HaltMusic();
Mix_FreeMusic(music);
for (unsigned int i = 0; i < sounds.size(); ++i) {
Mix_FreeChunk(sounds[i]);
}
Mix_CloseAudio();
// std::clock_t duration = std::clock() - start;
// std::cout << "Clean up took " << duration << " ticks\n";
}
SDLSound::SDLSound() :
volume(SDL_MIX_MAXVOLUME),
currentSound(-1),
music(NULL),
audioRate(22050),
audioChannels(2),
audioBuffers(4096),
sounds(),
channels()
{
if(Mix_OpenAudio(audioRate, MIX_DEFAULT_FORMAT, audioChannels,
audioBuffers)){
throw string("Unable to open audio!");
}
music = Mix_LoadMUS("sound/Robobop.mp3");
// Need to install midi to play the following:
//music = Mix_LoadMUS("sound/ballad2.mid");
if (!music) throw string("Couldn't load Game Sound")+Mix_GetError();
startMusic();
sounds.reserve(2);
sounds.push_back( Mix_LoadWAV("sound/smack-1.wav") );
sounds.push_back( Mix_LoadWAV("sound/button-15.wav") );
for (unsigned int i = 0; i < sounds.size(); ++i) channels.push_back(i);
}
void SDLSound::toggleMusic() {
if( Mix_PausedMusic() ) {
Mix_ResumeMusic();
}
else {
Mix_PauseMusic();
}
}
void SDLSound::operator[](int index) {
if (currentSound >= 0) Mix_HaltChannel(currentSound);
currentSound = index;
Mix_VolumeChunk(sounds[index], volume);
channels[index] =
Mix_PlayChannel(channels[index], sounds[index], 0);
}
void SDLSound::startMusic() {
Mix_VolumeMusic(volume);
Mix_PlayMusic(music, -1);
}
void SDLSound::stopMusic() {
Mix_HaltMusic();
Mix_FreeMusic(music);
}