Advertisement
LBoksha

Write wave file

Jul 10th, 2021
1,053
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. #include <fstream>
  2. #include <string>
  3. #include <vector>
  4.  
  5.  
  6. void write_wave_file(std::string filename, int samplingrate, const std::vector<double> &data)
  7. {
  8.     std::ofstream outfile(filename.c_str(),std::ios::binary);
  9.     outfile.write("RIFF    WAVEfmt ",16);
  10.    
  11.     char pcmchunkcts[] = {16, 0, 0, 0, 1, 0, 1, 0, // chunksize (4), format (2), number of channels (2)
  12.         char(0xFF&(samplingrate >>  0)), char(0xFF&(samplingrate >>  8)),
  13.         char(0xFF&(samplingrate >> 16)), char(0xFF&(samplingrate >> 24)), // sampling rate (4)
  14.         char(0xFF&(samplingrate <<  1)), char(0xFF&(samplingrate >>  7)),
  15.         char(0xFF&(samplingrate >> 15)), char(0xFF&(samplingrate >> 23)), // byte rate (4)
  16.         2, 0, 16, 0}; // block align (2), bits per sample (2)
  17.     outfile.write(pcmchunkcts,20);
  18.     std::vector<char> bytedata(2*data.size(),0);
  19.     for (unsigned int i = 0; i < data.size(); i++)
  20.     {
  21.         unsigned int sample = 0xFFFF&(
  22.             std::max(0x8000,
  23.                      std::min(0x17FFF,
  24.                               int(0x10000+data[i]*0x8000))
  25.                      )
  26.         );
  27.         bytedata[2*i+0] = 0xFF&(sample >> 0);
  28.         bytedata[2*i+1] = 0xFF&(sample >> 8);
  29.     }
  30.     char datasize[] = {
  31.         char(0xFF&(bytedata.size() >>  0)), char(0xFF&(bytedata.size() >>  8)),
  32.         char(0xFF&(bytedata.size() >> 16)), char(0xFF&(bytedata.size() >> 24)) };
  33.     outfile.write("data",4);
  34.     outfile.write(datasize,4);
  35.     outfile.write(&(bytedata[0]),bytedata.size());
  36.     int totalsize = int(outfile.tellp()) - 8;
  37.     outfile.seekp(4);
  38.     char mainchunksize[] = {
  39.         char(0xFF&(totalsize >> 0)), char(0xFF&(totalsize >>  8)),
  40.         char(0xFF&(totalsize >> 16)), char(0xFF&(totalsize >> 24)) };
  41.     outfile.write(mainchunksize,4);
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement