Skip to content

Instantly share code, notes, and snippets.

@acdimalev
Created April 10, 2022 00:56
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 acdimalev/53918e150a503c8f4b3eb44951c1f3fc to your computer and use it in GitHub Desktop.
Save acdimalev/53918e150a503c8f4b3eb44951c1f3fc to your computer and use it in GitHub Desktop.
// modprobe snd_pcm_oss
#include <fcntl.h>
#include <linux/soundcard.h>
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <unistd.h>
static inline void err(char *str)
{ perror(str); exit(1); }
static inline void errif(bool condition, char *str)
{ if (condition) err(str); }
int main(int argc, char **argv)
{ int dsp = 0;
{ // open and configure DSP device
char dsp_device[] = "/dev/dsp2";
int
channels = 2
, frequency = 48000
, format = AFMT_S16_LE
;
dsp = open(dsp_device, O_WRONLY);
errif (!dsp, dsp_device);
errif (!!ioctl(dsp, SNDCTL_DSP_SETFMT, &format), "sndctl_dsp_setfmt");
errif (!!ioctl(dsp, SNDCTL_DSP_CHANNELS, &channels), "sndctl_dsp_channels");
errif (!!ioctl(dsp, SNDCTL_DSP_SPEED, &frequency), "dnsctl_dsp_speed");
}
{ // generate sine wave
int period = 48000 / 261.63; // Middle C in A440
for (int i = 0; ; i = (i+1) % period)
{ float x = 2 * M_PI * i / period;
float y = sin(x);
int16_t sample[2] = { INT16_MAX * y, INT16_MAX * y };
write(dsp, sample, sizeof(sample));
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment