Skip to content

Instantly share code, notes, and snippets.

@vthanki
Created August 2, 2017 05:32
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 vthanki/8147dad736957b77d648a73b4b2568d7 to your computer and use it in GitHub Desktop.
Save vthanki/8147dad736957b77d648a73b4b2568d7 to your computer and use it in GitHub Desktop.
Sine wave generator (buggy)
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <math.h>
#include <malloc.h>
struct wavehdr {
char chunk_id[4];
int chunk_size;
char format[4];
char subchunk1_id[4];
int subchunk1_size;
short audio_fmt;
short nr_channels;
int sample_rate;
int byte_rate;
short block_align;
short bits_per_sample;
char subchunk2_id[4];
int subchunk2_size;
} __attribute__ ((packed));
int main(int argc, char *argv[])
{
struct stat fbuf;
int fsize;
struct wavehdr whdr;
int fdout;
int read_bytes = 0;
int sample_rate = 44100;
int len_in_sec = atoi(argv[1]);
int sine_freq = atoi(argv[2]);
int nr_samples = len_in_sec * sample_rate;
double i, period;
int samples_per_sine_hz = sample_rate / sine_freq;
short int *buf;
int index;
strcpy(whdr.chunk_id, "RIFF");
strcpy(whdr.format, "WAVE");
strcpy(whdr.subchunk1_id, "fmt ");
strcpy(whdr.subchunk2_id, "data");
whdr.subchunk1_size = 0x10; //Fixed for PCM
whdr.audio_fmt = 0x1; //PCM
whdr.nr_channels = 2; //stereo
whdr.sample_rate = sample_rate; //CD Quality
whdr.bits_per_sample = 16;
whdr.byte_rate = (whdr.sample_rate * whdr.nr_channels * whdr.bits_per_sample) / 8;
whdr.block_align = whdr.nr_channels * whdr.bits_per_sample / 8;
whdr.subchunk2_size = nr_samples * whdr.nr_channels * whdr.bits_per_sample / 8;
whdr.chunk_size = 4 + (8 + whdr.subchunk1_size) + (8 + whdr.subchunk2_size);
fdout = open("/tmp/testwave", O_RDWR | O_CREAT, 0644);
if (fdout < 0) {
printf("create failed\n");
goto exit;
}
write(fdout, &whdr, sizeof(whdr));
period = (float) (360.0 / samples_per_sine_hz);
i = 0;
buf = (short int *)malloc(32*1024*sizeof(short int));
if (!buf) {
printf("Failed to allocate memory\n");
close(fdout);
}
index = 0;
while (nr_samples--) {
double dx = sin((double)i * M_PI/180) ;
short int x = ((short int) (sin((double)i * M_PI/180) * 0x7fff));
// printf("x = %x dx = %lf\n",x, dx);
if (index < 32*1024)
buf[index++] = x;
else {
write(fdout, buf, index * sizeof(short int));
write(fdout, buf, index * sizeof(short int));
index = 0;
}
i += period;
if (i >= 360)
i -= 360;
}
if (index) {
write(fdout, buf, index * sizeof(short int));
write(fdout, buf, index * sizeof(short int));
free(buf);
}
close(fdout);
exit:
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment