Created
March 26, 2021 05:21
-
-
Save antoinefortin/e05ec2f1302209be0e1bd85ea0531eaa 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 <iostream> | |
#include <cmath> | |
#include <fstream> | |
#define M_PI 3.1415926 | |
using namespace std; | |
const int sampleRate = 44100; | |
const int bitDepth = 16; | |
class SineOscillator { | |
float frequency, amplitude, angle = 0.0f, offset = 0.0f; | |
public: | |
SineOscillator(float freq, float amp) : frequency(freq), amplitude(amp) { | |
offset = 2 * M_PI * frequency / sampleRate; | |
} | |
float process() { | |
auto sample = amplitude * sin(angle); | |
angle += offset; | |
return sample; | |
// Asin(2pif/sr) | |
} | |
}; | |
void writeToFile(ofstream& file, int value, int size) { | |
file.write(reinterpret_cast<const char*> (&value), size); | |
} | |
int main() { | |
ofstream audioFile; | |
audioFile.open("waveform.wav", ios::binary); | |
//Header chunk | |
audioFile << "RIFF"; | |
audioFile << "----"; | |
audioFile << "WAVE"; | |
// Format chunk | |
audioFile << "fmt "; | |
writeToFile(audioFile, 16, 4); // Size | |
writeToFile(audioFile, 1, 2); // Compression code | |
writeToFile(audioFile, 1, 2); // Number of channels | |
writeToFile(audioFile, sampleRate, 4); // Sample rate | |
writeToFile(audioFile, sampleRate * bitDepth / 8, 4); // Byte rate | |
writeToFile(audioFile, bitDepth / 8, 2); // Block align | |
writeToFile(audioFile, bitDepth, 2); // Bit depth | |
//Data chunk | |
audioFile << "data"; | |
audioFile << "----"; | |
int preAudioPosition = audioFile.tellp(); | |
auto maxAmplitude = pow(2, bitDepth - 1) - 1; | |
int duration = 12; | |
SineOscillator sineOscillator(440, 0.5); | |
SineOscillator sineOscillator2(880, 0.5); | |
SineOscillator sineOscillator3(880 * 2, 0.5); | |
/* Audio render loop */ | |
for (int i = 0; i < sampleRate * duration; i++) { | |
auto sample = sineOscillator.process(); | |
auto sample2 = sineOscillator2.process(); | |
auto sample3 = sineOscillator3.process(); | |
int intSample = static_cast<int> ( | |
(sample * maxAmplitude) + | |
(sample2 * maxAmplitude) + | |
(sample3 * maxAmplitude)) | |
* .05; | |
writeToFile(audioFile, intSample, 2); | |
} | |
int postAudioPosition = audioFile.tellp(); | |
audioFile.seekp(preAudioPosition - 4); | |
writeToFile(audioFile, postAudioPosition - preAudioPosition, 4); | |
audioFile.seekp(4, ios::beg); | |
writeToFile(audioFile, postAudioPosition - 8, 4); | |
audioFile.close(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment