Created
February 15, 2023 22:21
-
-
Save Infinitusvoid/4ceec8ce1575e4270c7d34fea7aa5668 to your computer and use it in GitHub Desktop.
C++ : How to write WAV audio file?
This file contains hidden or 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 <fstream> | |
#include <cmath> | |
int write_wav_sound() | |
{ | |
const int SAMPLE_RATE = 44100; | |
const double PI = 3.14159265359; | |
const double FREQUENCY = 440.0; | |
const double DURATION = 2.0; | |
const int NUM_SAMPLES = SAMPLE_RATE * DURATION; | |
const int BITS_PER_SAMPLE = 16; | |
std::ofstream out("C:/Users/CosmosXYZ/Desktop/Data_TheD/output.wav", std::ios::binary); | |
if (!out) { | |
return 1; | |
} | |
const int BYTE_RATE = SAMPLE_RATE * BITS_PER_SAMPLE / 8; | |
const int BLOCK_ALIGN = BITS_PER_SAMPLE / 8; | |
const int DATA_SIZE = NUM_SAMPLES * BLOCK_ALIGN; | |
out.write("RIFF", 4); | |
out.write(reinterpret_cast<const char*>(&DATA_SIZE + 36), 4); | |
out.write("WAVE", 4); | |
out.write("fmt ", 4); | |
int format_chunk_size = 16; | |
out.write(reinterpret_cast<const char*>(&format_chunk_size), 4); | |
short audio_format = 1; | |
out.write(reinterpret_cast<const char*>(&audio_format), 2); | |
short num_channels = 1; | |
out.write(reinterpret_cast<const char*>(&num_channels), 2); | |
out.write(reinterpret_cast<const char*>(&SAMPLE_RATE), 4); | |
out.write(reinterpret_cast<const char*>(&BYTE_RATE), 4); | |
out.write(reinterpret_cast<const char*>(&BLOCK_ALIGN), 2); | |
out.write(reinterpret_cast<const char*>(&BITS_PER_SAMPLE), 2); | |
out.write("data", 4); | |
out.write(reinterpret_cast<const char*>(&DATA_SIZE), 4); | |
for (int i = 0; i < NUM_SAMPLES; ++i) { | |
double t = static_cast<double>(i) / SAMPLE_RATE; | |
double sample = 32767 * sin(2 * PI * FREQUENCY * t); | |
short int int_sample = static_cast<short int>(sample); | |
out.write(reinterpret_cast<const char*>(&int_sample), 2); | |
} | |
} | |
int main() | |
{ | |
return write_wav_sound(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment