I’m having an issue playing .ogg files. When I play one there is weird noise included.
Any idea?
Here is a full reproduction. Everything else it needs to run is stb/stb_vorbis.c at master · nothings/stb · GitHub (you can simply copy-paste this) and any .ogg file.
#define SDL_MAIN_USE_CALLBACKS 1
#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>
#include "stb_vorbis.c"
static SDL_Window *window = NULL;
static SDL_Renderer *renderer = NULL;
static SDL_AudioStream *stream = NULL;
stb_vorbis *decoder;
stb_vorbis_info info;
static void SDLCALL FeedTheAudioStreamMore(void *userdata, SDL_AudioStream *astream, int additional_amount, int total_amount)
{
additional_amount /= sizeof (float);
while (additional_amount > 0) {
float samples[8096];
const int total = SDL_min(additional_amount, SDL_arraysize(samples));
stb_vorbis_get_samples_float_interleaved(
decoder,
info.channels,
samples,
total
);
SDL_PutAudioStreamData(astream, samples, total * sizeof (float));
additional_amount -= total;
}
}
SDL_AppResult SDL_AppInit(void **appstate, int argc, char *argv[])
{
// load the entire .ogg file into memory
FILE* fp = fopen("any_ogg_file.ogg", "r");
fseek(fp, 0, SEEK_END);
int size = ftell(fp);
fseek(fp, 0, SEEK_SET);
void* data = malloc(size);
fread(data, 1, size, fp);
int err;
decoder = stb_vorbis_open_memory(data, size, &err, NULL);
info = stb_vorbis_get_info(decoder);
if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO)) {
SDL_Log("Couldn't initialize SDL: %s", SDL_GetError());
return SDL_APP_FAILURE;
}
if (!SDL_CreateWindowAndRenderer("examples/audio/simple-playback-callback", 640, 480, 0, &window, &renderer)) {
SDL_Log("Couldn't create window/renderer: %s", SDL_GetError());
return SDL_APP_FAILURE;
}
SDL_AudioSpec spec;
spec.channels = info.channels;
spec.format = SDL_AUDIO_F32;
spec.freq = info.sample_rate;
stream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec, FeedTheAudioStreamMore, NULL);
if (!stream) {
SDL_Log("Couldn't create audio stream: %s", SDL_GetError());
return SDL_APP_FAILURE;
}
SDL_ResumeAudioStreamDevice(stream);
return SDL_APP_CONTINUE;
}
SDL_AppResult SDL_AppEvent(void *appstate, SDL_Event *event)
{
if (event->type == SDL_EVENT_QUIT) {
return SDL_APP_SUCCESS;
}
return SDL_APP_CONTINUE;
}
SDL_AppResult SDL_AppIterate(void *appstate)
{
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
return SDL_APP_CONTINUE;
}
void SDL_AppQuit(void *appstate, SDL_AppResult result)
{
}
Basically the question is: how do I play .ogg files correctly?