_ _
| |_ ___ __| |____ ___ _ _
| __/ _ \/ _` |_ / / _ \ | | |
| || __/ (_| |/ / | __/ |_| |
\__\___|\__,_/___(_)___|\__,_|
Audio synthesizer experiment in C using aplay
//
// synth.c - audio synth experiment
// Author: Ted Burke
// Date: 13 Apr 2024
//
// To compile:
// gcc synth.c -o synth -lm
//
// To run:
// ./synth | aplay -f S16_LE -c1 -r44100
//
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#include <unistd.h>
int main()
{
int n, N; // sample number, number of samples
double f = 400; // fundamental harmonic freq
double Fs = 44100; // sampling freq
int16_t s; // used to store one sample
int16_t *buf; // pointer to audio buffer
// Allocate buffer to store audio samples
N = Fs * 5; // specify 5-second buffer
buf = malloc(N * sizeof(s));
if (!buf) return 1;
// Generate waveform with several harmonics
for (n = 0 ; n < N ; ++n)
{
s = 8000 * sin(2.0 * M_PI * f * n / Fs);
s += 8000 * sin(2.0 * M_PI * 3*f * n / Fs);
s += 8000 * sin(2.0 * M_PI * 5*f * n / Fs);
s += 8000 * sin(2.0 * M_PI * 7*f * n / Fs);
buf[n] = s;
}
// Write audio data to stdout
fwrite(buf, sizeof(s), N, stdout);
// Clean up and exit
free(buf);
return 0;
}