Skip to content

Instantly share code, notes, and snippets.

@dreamlayers
Created February 3, 2014 01:13
Show Gist options
  • Save dreamlayers/8777540 to your computer and use it in GitHub Desktop.
Save dreamlayers/8777540 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <SDL/SDL.h>
#ifdef EMSCRIPTEN
#include <emscripten.h>
#else
#include <unistd.h>
#endif
#define NUM_FRAMES 1024
#define NUM_CHANNELS 2
#define NUM_SAMPLES (NUM_FRAMES * NUM_CHANNELS)
#define FREQ_MUL 4
Sint16 buffer[NUM_SAMPLES];
void fill_buffer(void) {
int i, j;
Sint16 *p = &buffer[0];
for (i = 0; i < NUM_SAMPLES / NUM_CHANNELS; i++) {
Sint16 val = (Sint16)(sin(((double)i * FREQ_MUL / NUM_FRAMES)
* M_PI * 2) * 30000);
for (j = 0; j < NUM_CHANNELS; j++) {
*(p++) = val;
}
}
}
void audio_callback(void *udata, Uint8 *stream, int len) {
if (len != sizeof(buffer)) {
printf("Expected len == %i but got %i\n", (int)sizeof(buffer), len);
abort();
}
memcpy(stream, buffer, len);
}
#ifdef EMSCRIPTEN
void main_loop(void) {
}
#endif
int main(void) {
SDL_AudioSpec wanted;
fill_buffer();
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);
/* Set the audio format */
wanted.freq = 44100;
wanted.format = AUDIO_S16SYS;
wanted.channels = NUM_CHANNELS;
/* Why this difference? */
#ifdef EMSCRIPTEN
wanted.samples = NUM_FRAMES;
#else
wanted.samples = NUM_SAMPLES;
#endif
wanted.callback = audio_callback;
wanted.userdata = NULL;
/* Open the audio device, forcing the desired format */
if (SDL_OpenAudio(&wanted, NULL) < 0) {
printf("Couldn't open audio: %s\n", SDL_GetError());
return(-1);
}
SDL_PauseAudio(0);
#ifdef EMSCRIPTEN
emscripten_set_main_loop(main_loop, 1, 0);
#else
sleep(100);
#endif
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment