Created
May 3, 2011 17:28
-
-
Save EmilHernvall/953775 to your computer and use it in GitHub Desktop.
Experiment with generating sound in wave-format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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