I’m simply trying to play a sine wave, but all I hear is choppy sound, much like a ‘machine gun’ effect. Extract of relevant code (note I’m running with VSYNC renderer)
SDL_AudioSpec actual_audio_spec = {0};
SDL_AudioSpec desired_audio_spec = {
.freq = 48000,
.format = AUDIO_S16LSB,
.channels = 2,
.samples = (48000 * (sizeof(i16) * 2)) / best_display_mode.refresh_rate
};
SDL_AudioDeviceID audio_dev = SDL_OpenAudioDevice(NULL, 0, &desired_audio_spec, &actual_audio_spec, 0);
if (audio_dev == 0) {
// TODO(Ryan): Logging
return EXIT_FAILURE;
}
if (actual_audio_spec.format != desired_audio_spec.format) {
// TODO(Ryan): Logging
return EXIT_FAILURE;
}
u32 num_samples_to_fill_per_frame = actual_audio_spec.freq / 15;
u32 target_bytes_to_write = num_samples_to_fill_per_frame * sizeof(i16) * 2;
i16 audio_data[num_samples_to_fill_per_frame * 2];
u32 audio_wave_pitch = 440;
r32 audio_wave_volume = 3000;
u32 audio_wave_period = actual_audio_spec.freq / audio_wave_pitch;
r32 tsine = 0.0f;
for (u32 sample_index = 0; sample_index < num_samples_to_fill_per_frame; ++sample_index) {
r32 sine_value = sinf(tsine);
i16 sample_value = (i16)(sine_value * audio_wave_volume);
audio_data[sample_index++] = sample_value;
audio_data[sample_index] = sample_value;
tsine += 2.0f * M_PI * 1.0f / (r32)audio_wave_period;
}
SDL_QueueAudio(audio_dev, audio_data, target_bytes_to_write - SDL_GetQueuedAudioSize(audio_dev));
SDL_PauseAudioDevice(audio_dev, 0);
bool want_to_run = true;
while (want_to_run) {
SDL_Event event = {0};
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
want_to_run = false;
}
}
for (u32 sample_index = 0; sample_index < num_samples_to_fill_per_frame; ++sample_index) {
r32 sine_value = sinf(tsine);
i16 sample_value = (i16)(sine_value * audio_wave_volume);
audio_data[sample_index++] = sample_value;
audio_data[sample_index] = sample_value;
tsine += 2.0f * M_PI * 1.0f / (r32)audio_wave_period;
}
SDL_QueueAudio(audio_dev, audio_data, target_bytes_to_write - SDL_GetQueuedAudioSize(audio_dev));
SDL_RenderPresent();
}