Skip to content

Commit

Permalink
examples: use doubles to generate sine waves and avoid distortion
Browse files Browse the repository at this point in the history
  • Loading branch information
mausimus authored and icculus committed Jan 13, 2025
1 parent 307e6f2 commit 03a3c19
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 4 deletions.
4 changes: 2 additions & 2 deletions examples/audio/01-simple-playback/simple-playback.c
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,9 @@ SDL_AppResult SDL_AppIterate(void *appstate)
for (i = 0; i < SDL_arraysize(samples); i++) {
/* You don't have to care about this math; we're just generating a simple sine wave as we go.
https://en.wikipedia.org/wiki/Sine_wave */
const float time = total_samples_generated / 8000.0f;
const double time = total_samples_generated / 8000.0;

This comment has been minimized.

Copy link
@expikr

expikr Jan 13, 2025

Contributor

I recommend this change which uses the SDL_PI_D macro and modulus operator on the integer samples to prevent precision loss at longer times:

-           const double time = total_samples_generated / 8000.0;
-           const int sine_freq = 500;   /* run the wave at 500Hz */
-           samples[i] = (float)SDL_sin(6.283185 * sine_freq * time);
+           const int sine_freq = 500;   /* run the wave at 500Hz */
+           const int cycle = sine_freq * 8000;
+           const int phase = total_samples_generated % cycle;
+           const double time = phase / 8000.0
+           samples[i] = (float)SDL_sin(2 * SDL_PI_D * time);

Same goes for the other file.

This comment has been minimized.

Copy link
@slouken

slouken Jan 13, 2025

Collaborator

Can you create a PR so this doesn't get lost?

const int sine_freq = 500; /* run the wave at 500Hz */
samples[i] = SDL_sinf(6.283185f * sine_freq * time);
samples[i] = (float)SDL_sin(6.283185 * sine_freq * time);
total_samples_generated++;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ static void SDLCALL FeedTheAudioStreamMore(void *userdata, SDL_AudioStream *astr
for (i = 0; i < total; i++) {
/* You don't have to care about this math; we're just generating a simple sine wave as we go.
https://en.wikipedia.org/wiki/Sine_wave */
const float time = total_samples_generated / 8000.0f;
const double time = total_samples_generated / 8000.0;
const int sine_freq = 500; /* run the wave at 500Hz */
samples[i] = SDL_sinf(6.283185f * sine_freq * time);
samples[i] = (float)SDL_sin(6.283185 * sine_freq * time);
total_samples_generated++;
}

Expand Down

0 comments on commit 03a3c19

Please sign in to comment.