Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Experiment with generating sound in wave-format
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct GlobalFormat {
unsigned int id;
unsigned int size;
unsigned int type;
};
struct FormatChunk {
unsigned int dwId;
unsigned int dwSize;
short wFormatTag;
unsigned short wChannels;
unsigned long dwSamplesPerSec;
unsigned long dwAvgBytesPerSec;
unsigned short wBlockAlign;
unsigned short wBitsPerSample;
};
int main(int argc, char** argv)
{
struct FormatChunk fmt;
fmt.dwId = 0x20746d66; // "fmt "
fmt.dwSize = 16;
fmt.wFormatTag = 1;
fmt.wChannels = 1;
fmt.wBitsPerSample = 16;
fmt.dwSamplesPerSec = 22050;
fmt.dwAvgBytesPerSec = fmt.dwSamplesPerSec * fmt.wBitsPerSample/8;
fmt.wBlockAlign = 4;
if (argc != 5) {
printf("usage: ./generatewav amplitude frequency length filename\n");
return 0;
}
unsigned short amplitude = (unsigned short)atoi(argv[1]);
double frequency = (double)atoi(argv[2]);
int length = atoi(argv[3]) * fmt.dwSamplesPerSec * fmt.wChannels * fmt.wBitsPerSample / 8;
char* fileName = argv[4];
FILE* fh = fopen(fileName, "w");
struct GlobalFormat format;
format.id = 0x46464952; // RIFF
format.size = length;
format.type = 0x45564157; // WAVE
fwrite(&format, sizeof(struct GlobalFormat), 1, fh);
fwrite(&fmt, sizeof(struct FormatChunk), 1, fh);
unsigned int dataId = 0x61746164;
fwrite(&dataId, sizeof(unsigned int), 1, fh);
unsigned int dataLength = length - 12 - 16 - 12;
fwrite(&dataLength, sizeof(unsigned int), 1, fh);
int i;
double period = 2*M_PI/((double)fmt.dwSamplesPerSec/frequency);
printf("frequency: %f\n", frequency);
printf("period: %f\n", period);
printf("amplitude: %d\n", amplitude);
for (i = 0; i < dataLength; i += 2) {
if (i > 100) {
break;
}
unsigned short sample = amplitude * (1 + sin(period*(double)i));
printf("%hd\n", sample);
fwrite(&sample, sizeof(unsigned short), 1, fh);
}
fclose(fh);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment