Created
February 3, 2023 00:27
-
-
Save datajake1999/7d379cbfaff17930c221bf7630c8f547 to your computer and use it in GitHub Desktop.
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> | |
#ifndef M_PI | |
#define M_PI 3.14159265358979323846 | |
#endif | |
void GenerateTone(double frequency, double sampleRate, double amplitude, double fadeTime, double *buffer, int length) | |
{ | |
double phase; | |
double phaseIncrement; | |
double *fadeSamples; | |
int fadeLength; | |
int centerLength; | |
int i; | |
fadeLength = (int)(fadeTime*sampleRate); | |
centerLength = length-(fadeLength*2); | |
if (centerLength < 0) | |
{ | |
centerLength = 0; | |
} | |
if ((fadeLength*2)+centerLength > length) | |
{ | |
return; | |
} | |
fadeSamples = (double *)malloc(fadeLength*sizeof(double)); | |
if (!fadeSamples) | |
{ | |
return; | |
} | |
phaseIncrement = 2*M_PI*0.25/(double)fadeLength; | |
phase = 0; | |
for (i = 0; i < fadeLength; i++) | |
{ | |
double sample = sin(phase); | |
fadeSamples[i] = sample*sample; | |
phase += phaseIncrement; | |
if (phase >= 2*M_PI) | |
{ | |
phase -= 2*M_PI; | |
} | |
} | |
phaseIncrement = 2*M_PI*frequency/sampleRate; | |
phase = 0; | |
for (i = 0; i < fadeLength; i++) | |
{ | |
double sample = amplitude*sin(phase); | |
phase += phaseIncrement; | |
if (phase >= 2*M_PI) | |
{ | |
phase -= 2*M_PI; | |
} | |
*buffer = fadeSamples[i]*sample; | |
buffer++; | |
} | |
for (i = 0; i < centerLength; i++) | |
{ | |
double sample = amplitude*sin(phase); | |
phase += phaseIncrement; | |
if (phase >= 2*M_PI) | |
{ | |
phase -= 2*M_PI; | |
} | |
*buffer = sample; | |
buffer++; | |
} | |
for (i = fadeLength-1; i>= 0; i--) | |
{ | |
double sample = amplitude*sin(phase); | |
phase += phaseIncrement; | |
if (phase >= 2*M_PI) | |
{ | |
phase -= 2*M_PI; | |
} | |
*buffer = fadeSamples[i]*sample; | |
buffer++; | |
} | |
free(fadeSamples); | |
} | |
int main() | |
{ | |
double buffer[44100]; | |
FILE *out; | |
GenerateTone(440, 44100, 1, 0.002, buffer, sizeof(buffer)/sizeof(double)); | |
out = fopen("output", "wb"); | |
fwrite(buffer, 1, sizeof(buffer), out); | |
fclose(out); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment