ampler/audio.c

66 lines
1.6 KiB
C
Raw Normal View History

2021-12-18 20:58:21 +00:00
// audio.c
int audio_frame(Ampler_state *state) {
int queued = SDL_GetQueuedAudioSize(state -> playdev);
queued /= sizeof s16; // queued is in bytes
2021-12-19 22:44:48 +00:00
if queued > FRAME_SAMPLES * CHANNELS * 2 do return 0;
2021-12-18 20:58:21 +00:00
// else puts("queued audio.");
2021-12-19 22:44:48 +00:00
static s16 frame[SAMPLE_RATE * CHANNELS * 7] = { 0 };
for int i = 0; i < arraylen(frame); i += CHANNELS do {
int vol = 64;
frame[i] = ((s16) (state -> track_l[i])) * vol;
frame[i + 1] = ((s16) (state -> track_r[i])) * vol;
2021-12-18 20:58:21 +00:00
}
2021-12-19 22:44:48 +00:00
if SDL_QueueAudio(state -> playdev, frame, sizeof frame) do
2021-12-18 20:58:21 +00:00
puts(SDL_GetError());
return 1; // audio was qued
}
2021-12-19 22:44:48 +00:00
void load_track(Ampler_state *state) {
SDL_AudioSpec spec;
s16 *buffer = NULL;
u32 bytes = 0;
SDL_LoadWAV("sample.wav", &spec, &buffer, &bytes);
if spec.format != AUDIO_S16 do {
puts("error: sample.wav is not s16");
return;
}
const int len = bytes / sizeof s16;
// TODO: Use floats to print out total number of seconds
printf("loading sample.wav\n");
s8 *tracks[] = { state -> track_l, state -> track_r, };
for int i = 0; i < len; i += spec.channels do
for int c = 0; c < spec.channels; c++ do {
tracks[c][i] = (s8) (buffer[i + c] >> 8);
}
SDL_FreeWAV((void *) buffer);
}
void load_track_f32() { // idk if we're ever gonna be loading floats
/*
f32 max = 0.0f;
for int i = 0; i < len; i++ do
if buffer[i] > max do
max = buffer[i];
else if buffer[i] < -max do
max = -buffer[i];
printf("%f max\n", max);
for int i = 0; i < len; i += 2 do {
buffer[i] /= max;
buffer[i + 1] /= max;
state -> track_l[i] = ((s8)(buffer[i] * 127.0f));
state -> track_r[i] = ((s8)(buffer[i + 1] * 127.0f));
}
*/
}