-
Notifications
You must be signed in to change notification settings - Fork 0
/
audio.cc
69 lines (61 loc) · 1.4 KB
/
audio.cc
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 <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
#include "audio.h"
#include "log.h"
#define ALOG(...) log("A", __VA_ARGS__)
extern bool sfx;
namespace trek {
const char *const GROOVE_PATH = "art/nonfree.mp3";
static Mix_Music *groove;
static Mix_Chunk *sounds[NUM_SOUNDS];
void init_audio() {
if (!sfx) {
return;
}
if (SDL_Init(SDL_INIT_AUDIO) == -1) {
ALOG("couldn't init SDL: %s", SDL_GetError());
sfx = false;
return;
}
if (Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1) {
ALOG("couldn't open mixer: %s", Mix_GetError());
sfx = false;
return;
}
if ((groove = Mix_LoadMUS(GROOVE_PATH)) == nullptr) {
ALOG("couldn't load music: %s", Mix_GetError());
sfx = false;
return;
}
for (int i = 0; i < (int)NUM_SOUNDS; i++) {
if ((sounds[i] = Mix_LoadWAV(SFX_PATH[i])) == nullptr) {
ALOG("couldn't load sound effect %s: %s", SFX_PATH[i], Mix_GetError());
sfx = false;
return;
}
}
}
void play_sound(Sound sound) {
if (sfx && sounds[sound] != nullptr) {
Mix_PlayChannel(-1, sounds[sound], 0);
}
}
void play_music() {
if (sfx && groove != nullptr) {
Mix_PlayMusic(groove, -1);
}
}
void cleanup_audio() {
for (int i = 0; i < (int)NUM_SOUNDS; i++) {
if (sounds[i] != nullptr) {
Mix_FreeChunk(sounds[i]);
}
}
if (groove != nullptr) {
Mix_FreeMusic(groove);
}
if (sfx) {
SDL_Quit();
}
}
}