Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- #include <string>
- #include <vector>
- void write_wave_file(std::string filename, int samplingrate, const std::vector<double> &data)
- {
- std::ofstream outfile(filename.c_str(),std::ios::binary);
- outfile.write("RIFF WAVEfmt ",16);
- char pcmchunkcts[] = {16, 0, 0, 0, 1, 0, 1, 0, // chunksize (4), format (2), number of channels (2)
- char(0xFF&(samplingrate >> 0)), char(0xFF&(samplingrate >> 8)),
- char(0xFF&(samplingrate >> 16)), char(0xFF&(samplingrate >> 24)), // sampling rate (4)
- char(0xFF&(samplingrate << 1)), char(0xFF&(samplingrate >> 7)),
- char(0xFF&(samplingrate >> 15)), char(0xFF&(samplingrate >> 23)), // byte rate (4)
- 2, 0, 16, 0}; // block align (2), bits per sample (2)
- outfile.write(pcmchunkcts,20);
- std::vector<char> bytedata(2*data.size(),0);
- for (unsigned int i = 0; i < data.size(); i++)
- {
- unsigned int sample = 0xFFFF&(
- std::max(0x8000,
- std::min(0x17FFF,
- int(0x10000+data[i]*0x8000))
- )
- );
- bytedata[2*i+0] = 0xFF&(sample >> 0);
- bytedata[2*i+1] = 0xFF&(sample >> 8);
- }
- char datasize[] = {
- char(0xFF&(bytedata.size() >> 0)), char(0xFF&(bytedata.size() >> 8)),
- char(0xFF&(bytedata.size() >> 16)), char(0xFF&(bytedata.size() >> 24)) };
- outfile.write("data",4);
- outfile.write(datasize,4);
- outfile.write(&(bytedata[0]),bytedata.size());
- int totalsize = int(outfile.tellp()) - 8;
- outfile.seekp(4);
- char mainchunksize[] = {
- char(0xFF&(totalsize >> 0)), char(0xFF&(totalsize >> 8)),
- char(0xFF&(totalsize >> 16)), char(0xFF&(totalsize >> 24)) };
- outfile.write(mainchunksize,4);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement