Skip to content

Instantly share code, notes, and snippets.

@MurageKibicho
Created February 23, 2024 08:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MurageKibicho/0f79641f3ff40029193e7e8cfe6dbc08 to your computer and use it in GitHub Desktop.
Save MurageKibicho/0f79641f3ff40029193e7e8cfe6dbc08 to your computer and use it in GitHub Desktop.
SDL2 Play float audio
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <SDL2/SDL.h>
#define SAMPLE_RATE 44100
#define CHANNELS 1
#define BUFFER_SIZE 4096
#ifndef AUDIO_F32SYS
#define AUDIO_F32SYS 0x8120
#endif
size_t GetFileSize(char *fileName){FILE *fp = fopen(fileName, "rb");assert(fp != NULL);fseek(fp, 0L, SEEK_END);size_t currentFileSize = ftell(fp);rewind(fp);fclose(fp);return currentFileSize;}
void PlayRawAudio(size_t numberOfAudioSamples, float *audioSamples)
{
if(SDL_Init(SDL_INIT_AUDIO) < 0)
{
SDL_Log("Failed to initialize SDL: %s", SDL_GetError());
exit(-1);
}
SDL_AudioSpec desiredSpec, obtainedSpec;
SDL_zero(desiredSpec);
desiredSpec.freq = SAMPLE_RATE;
desiredSpec.format = AUDIO_F32SYS;
desiredSpec.channels = CHANNELS;
desiredSpec.samples = BUFFER_SIZE;
desiredSpec.callback = NULL;
SDL_AudioDeviceID audioDevice = SDL_OpenAudioDevice(NULL, 0, &desiredSpec, &obtainedSpec, 0);
if(audioDevice < 0)
{
SDL_Log("Failed to open audio device : %s", SDL_GetError());
SDL_Quit();
exit(-1);
}
/*Queue audio*/
int bytesToWrite = numberOfAudioSamples * sizeof(float);
if(SDL_QueueAudio(audioDevice, audioSamples, bytesToWrite) != 0)
{
SDL_Log("Failed to queue audio: (%s)", SDL_GetError());
SDL_CloseAudioDevice(audioDevice);
SDL_Quit();
exit(-1);
}
SDL_PauseAudioDevice(audioDevice, 0);
while(SDL_GetAudioDeviceStatus(audioDevice) == SDL_AUDIO_PLAYING)
{
//SDL_Delay(100);
}
SDL_CloseAudioDevice(audioDevice);
SDL_Quit();
}
int main()
{
char *audioFileName = "GeneratedAudio/audioData.raw";
size_t audioFileSize = GetFileSize(audioFileName);
size_t numberOfAudioSamples = audioFileSize / sizeof(float);
float *audioSamples = calloc(numberOfAudioSamples, sizeof(float));
FILE *audioInputFile = fopen(audioFileName, "r");assert(audioInputFile != NULL);
float currentSample = 0;
for(size_t i = 0; i < numberOfAudioSamples; i++)
{
fread(&currentSample, sizeof(float), 1, audioInputFile);
audioSamples[i] = currentSample;
}
PlayRawAudio(numberOfAudioSamples, audioSamples);
printf("%ld %.3f\n",numberOfAudioSamples, currentSample);
fclose(audioInputFile);
free(audioSamples);
return 0;
}
@MurageKibicho
Copy link
Author

Note: Change Sample rate to change frequency and speed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment