Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define NOMINMAX
- #include <windows.h>
- #include <iostream>
- #include <cmath>
- #include <limits>
- #include <fstream>
- #include <string>
- typedef signed short BitDepth;// 16bit audio
- typedef unsigned long long QWORD;
- const double pi = 3.141592653589;
- const DWORD samplerate = 44100;
- const WORD channels = 2;
- const unsigned short SOUND_DURATION = 1;// 1 second for example.
- const QWORD NUM_SAMPLES = SOUND_DURATION * samplerate * channels;
- void sineWave(BitDepth buffer[], double freq) {
- BitDepth amplitude = std::numeric_limits<BitDepth>::max()*0.5;
- QWORD c=0;
- double d=(samplerate/freq);
- for(QWORD i=0; i<NUM_SAMPLES; i+=channels) {
- double deg=360.0/d;
- buffer[i] = buffer[i+(1*(channels-1))] = sin((c++*deg)*pi/180)*amplitude;
- }
- }
- template<typename _Ty> void write(std::ofstream& stream, const _Ty& ty) {
- stream.write((const char*)&ty, sizeof(_Ty));
- }
- void writeWaveFile(const char* filename, BitDepth* buffer) {
- std::ofstream stream(filename, std::ios::binary);
- stream.write("RIFF", 4);
- ::write<int>(stream, 36+(NUM_SAMPLES*sizeof(BitDepth)));
- stream.write("WAVEfmt ", 8);
- ::write<int>(stream, 16);
- ::write<short>(stream, 1);
- ::write<unsigned short>(stream, channels);
- ::write<int>(stream, samplerate);
- ::write<int>(stream, samplerate*channels*sizeof(BitDepth));
- ::write<short>(stream, channels*sizeof(BitDepth));
- ::write<short>(stream, sizeof(BitDepth)*8);
- stream.write("data", 4);
- ::write<int>(stream, NUM_SAMPLES*sizeof(BitDepth));
- stream.write((const char*)&buffer[0], NUM_SAMPLES*sizeof(BitDepth));
- stream.close();
- }
- int main(int argc, char** argv) {
- SetConsoleTitleA("PCM Audio Example");
- std::string filename = "sine";
- BitDepth* buffer = new BitDepth[NUM_SAMPLES];
- memset(buffer, 0, NUM_SAMPLES*sizeof(BitDepth));
- sineWave(buffer, 1000.0);
- writeWaveFile(std::string(filename+std::string(".wav")).c_str(), buffer);
- delete[] buffer;
- std::cout << filename << ".wav written!" << std::endl;
- std::cin.get();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement