-
Notifications
You must be signed in to change notification settings - Fork 0
/
sound.cpp
82 lines (69 loc) · 1.88 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
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <string>
#include <iostream>
#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/2),
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("sounds/pinaColada.mp3");
// Need to install midi to play the following:
// music = Mix_LoadMUS("sound/ballad2.mid");
if (!music) throw string("Couldn't load song.wav")+Mix_GetError();
startMusic();
//1:11
sounds.push_back( Mix_LoadWAV("sounds/crabDie.wav") );
sounds.push_back( Mix_LoadWAV("sounds/ow.wav") );
sounds.push_back( Mix_LoadWAV("sounds/ploppp.wav") );
for (unsigned int i = 0; i < sounds.size(); ++i) channels.push_back(i);
std::cout << "Music and Sound is loaded" << std::endl;
}
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(-1, sounds[index], 0);
}
void SDLSound::startMusic() {
Mix_VolumeMusic(volume);
Mix_PlayMusic(music, -1);
}
void SDLSound::stopMusic() {
Mix_RewindMusic();
}
void SDLSound::restartMusic() {
music = Mix_LoadMUS("sounds/pinaColada.mp3");
startMusic();
}