This repository was archived by the owner on Mar 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathsomething_sound.cpp
More file actions
88 lines (73 loc) · 2.58 KB
/
something_sound.cpp
File metadata and controls
88 lines (73 loc) · 2.58 KB
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
83
84
85
86
87
88
#include "./something_sound.hpp"
void Sample_Mixer::clean()
{
for (size_t i = 0; i < SAMPLE_MIXER_CAPACITY; ++i) {
slots[i].playing = false;
}
}
void Sample_Mixer::play_sample(Index<Sample_S16> index)
{
for (size_t i = 0; i < SAMPLE_MIXER_CAPACITY; ++i) {
if (!slots[i].playing) {
slots[i].cursor = 0;
slots[i].index = index;
slots[i].playing = true;
return;
}
}
}
Sample_S16 load_wav_as_sample_s16(const char *file_path)
{
Sample_S16 sample = {};
SDL_AudioSpec want = {};
if (SDL_LoadWAV(file_path, &want, (Uint8**) &sample.audio_buf, &sample.audio_len) == nullptr) {
println(stderr, "SDL pooped itself: Failed to load ", file_path, ": ",
SDL_GetError());
abort();
}
assert(SDL_AUDIO_BITSIZE(want.format) == 16);
assert(SDL_AUDIO_ISLITTLEENDIAN(want.format));
assert(SDL_AUDIO_ISSIGNED(want.format));
assert(SDL_AUDIO_ISINT(want.format));
assert(want.freq == SOMETHING_SOUND_FREQ);
assert(want.channels == SOMETHING_SOUND_CHANNELS);
assert(want.samples == SOMETHING_SOUND_SAMPLES);
sample.audio_len /= 2;
return sample;
}
Sample_S16 load_wav_as_sample_s16(String_View file_path)
{
char *filepath_cstr = (char*) malloc(file_path.count + 1);
assert(filepath_cstr != NULL);
memcpy(filepath_cstr, file_path.data, file_path.count);
filepath_cstr[file_path.count] = '\0';
auto result = load_wav_as_sample_s16(filepath_cstr);
free(filepath_cstr);
return result;
}
void sample_mixer_audio_callback(void *userdata, Uint8 *stream, int len)
{
Sample_Mixer *mixer = (Sample_Mixer *)userdata;
int16_t *output = (int16_t *)stream;
size_t output_len = (size_t) len / sizeof(*output);
memset(stream, 0, (size_t) len);
for (size_t i = 0; i < SAMPLE_MIXER_CAPACITY; ++i) {
if (mixer->slots[i].playing) {
auto sample = assets.get_by_index(mixer->slots[i].index);
for (size_t j = 0; j < output_len; ++j) {
int16_t x = 0;
if (mixer->slots[i].cursor < sample.audio_len) {
x = sample.audio_buf[mixer->slots[i].cursor];
mixer->slots[i].cursor += 1;
}
output[j] = (int16_t) clamp(output[j] + x, (int) INT16_MIN, (int) INT16_MAX);
}
if (mixer->slots[i].cursor >= sample.audio_len) {
mixer->slots[i].playing = false;
}
}
}
for (size_t i = 0; i < output_len; ++i) {
output[i] = (int16_t) (output[i] * mixer->volume);
}
}