Last active
July 9, 2021 21:35
-
-
Save misterhat/fa14e263e547af78561d22bea2b6cbe2 to your computer and use it in GitHub Desktop.
play 8 bit unsigned PCM audio in SDL with C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <emscripten.h> | |
#include <SDL2/SDL.h> | |
#include <stdint.h> | |
#include <stdio.h> | |
#define BUFFER_SIZE 4096 | |
int main(int argc, char **argv) { | |
if (SDL_Init(SDL_INIT_AUDIO)) { | |
fprintf(stderr, "SDL_Init(): %s\n", SDL_GetError()); | |
return 1; | |
} | |
SDL_AudioSpec wanted; | |
wanted.freq = 44100; | |
wanted.format = AUDIO_U8; | |
wanted.channels = 2; | |
wanted.silence = 0; | |
wanted.samples = 1024; | |
wanted.callback = NULL; | |
if (SDL_OpenAudio(&wanted, NULL) < 0) { | |
fprintf(stderr, "SDL_OpenAudio(): %s\n", SDL_GetError()); | |
return 1; | |
} | |
FILE *fp_pcm = fopen("./2.raw", "rb"); | |
if (fp_pcm == NULL) { | |
fprintf(stderr, "can\'t open 2.raw"); | |
return 1; | |
} | |
char *pcm_buffer = (char *)malloc(BUFFER_SIZE); | |
SDL_PauseAudio(0); | |
emscripten_sleep(1000); | |
while (1) { | |
if (fread(pcm_buffer, 1, BUFFER_SIZE, fp_pcm) < 1) { | |
break; | |
} | |
SDL_QueueAudio(1, pcm_buffer, BUFFER_SIZE); | |
float bytesPerSecond = (44100 * 8 * 2) / 8; | |
SDL_Delay(((int) SDL_GetQueuedAudioSize(1) / bytesPerSecond * 1000) / 2); | |
//emscripten_sleep(((int) SDL_GetQueuedAudioSize(1) / bytesPerSecond * 1000) / 2); | |
} | |
free(pcm_buffer); | |
fclose(fp_pcm); | |
SDL_Quit(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment