Skip to content

Instantly share code, notes, and snippets.

@mkalte666
Last active May 21, 2019 17:37
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 mkalte666/b1c8a88a5882e83fec470329d7477607 to your computer and use it in GitHub Desktop.
Save mkalte666/b1c8a88a5882e83fec470329d7477607 to your computer and use it in GitHub Desktop.
#include "SDL.h"
#include <stdio.h>
#define SAMPLE_COUNT 4096
#define CHANNEL_COUNT 2
#define AUDIO_BUFFER_SIZE CHANNEL_COUNT*SAMPLE_COUNT
#define AUDIO_BUFFER_BYTES sizeof(short)*AUDIO_BUFFER_SIZE
int main(int argc, char** argv)
{
if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "SDL ERROR", "Init Error", nullptr);
SDL_Log("Something went wrong with SDL Init %s", SDL_GetError());
return 1;
}
short* buffer = (short*)malloc(AUDIO_BUFFER_BYTES);
if (!buffer) {
return 2;
}
double freq = 1000; // your freq
double level = 16384; // something not full clipping party
double K = 2.0 * M_PI / 48000.0 * freq; // constant
for (int i = 0; i < SAMPLE_COUNT; i++) {
float result = sin(i * K) * level; // calculate buffer value
// for each channel
for (int j = 0; j < CHANNEL_COUNT; j++) {
// get the location in the buffer and write the result
short* p = &buffer[i * CHANNEL_COUNT + j];
*p = (short)result; //... as short
}
}
SDL_AudioSpec requestAs;
SDL_AudioSpec actualAs;
SDL_zero(actualAs);
requestAs.freq = 48000;
requestAs.format = AUDIO_S16;
requestAs.channels = CHANNEL_COUNT;
requestAs.samples = 4096;
requestAs.callback = NULL;
const char* devName = SDL_GetAudioDeviceName(0, 0);
SDL_AudioDeviceID device = SDL_OpenAudioDevice(devName , 0, &requestAs, &actualAs, 1);
if (device == 0) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "SDL ERROR", "Cannot open audio device", nullptr);
SDL_Log("Something went wrong with SDL Audio device init %s", SDL_GetError());
return 3;
}
SDL_PauseAudioDevice(device, 0);
// one of these lasts less that .1 seconds!
SDL_QueueAudio(device, buffer, AUDIO_BUFFER_BYTES);
SDL_QueueAudio(device, buffer, AUDIO_BUFFER_BYTES);
SDL_QueueAudio(device, buffer, AUDIO_BUFFER_BYTES);
SDL_QueueAudio(device, buffer, AUDIO_BUFFER_BYTES);
SDL_QueueAudio(device, buffer, AUDIO_BUFFER_BYTES);
SDL_QueueAudio(device, buffer, AUDIO_BUFFER_BYTES);
SDL_QueueAudio(device, buffer, AUDIO_BUFFER_BYTES);
SDL_QueueAudio(device, buffer, AUDIO_BUFFER_BYTES);
SDL_QueueAudio(device, buffer, AUDIO_BUFFER_BYTES);
SDL_QueueAudio(device, buffer, AUDIO_BUFFER_BYTES);
SDL_QueueAudio(device, buffer, AUDIO_BUFFER_BYTES);
SDL_QueueAudio(device, buffer, AUDIO_BUFFER_BYTES);
SDL_QueueAudio(device, buffer, AUDIO_BUFFER_BYTES);
SDL_Delay(2000);
free(buffer);
SDL_CloseAudioDevice(device);
SDL_Quit();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment