1+ // Stolen and adapted from https://gist.github.com/nicolamontecchio/622276
2+
13#include " convert.hpp"
24
35void convert (const std::string &path) {
4- SF_INFO inFileInfo ;
5- SF_INFO outFileInfo ;
6- SNDFILE *inFile = sf_open (path.c_str (), SFM_READ , &inFileInfo );
7- if (inFile == nullptr )
6+ SNDFILE * sndfile ;
7+ SF_INFO sfinfo ;
8+ sndfile = sf_open (path.c_str (), SFM_READ , &sfinfo );
9+ if (sndfile == nullptr )
810 throw FileNotOpenedException (path);
9- else if (inFileInfo .channels != 2 ) {
10- sf_close (inFile );
11+ else if (sfinfo .channels != 2 ) {
12+ sf_close (sndfile );
1113 throw NotStereoException ();
1214 }
13-
14- float *inData = new float [inFileInfo.frames * 2 ];
15- float *outData = new float [inFileInfo.frames ];
16- sf_readf_float (inFile, inData, inFileInfo.frames );
17- for (int e = 0 ; e < inFileInfo.frames ; e++) {
18- for (int i = 0 ; i < 2 ; i++)
19- outData[e] += inData[e * 2 + i];
20- outData[e] /= 2 ;
15+ float *audioIn = new float [sfinfo.channels * sfinfo.frames ];
16+ sf_read_float (sndfile, audioIn, sfinfo.channels * sfinfo.frames );
17+ // mixdown
18+ float *audioOut = new float [sfinfo.frames ];
19+ for (int i = 0 ; i < sfinfo.frames ; i++)
20+ {
21+ audioOut[i] = 0 ;
22+ for (int j = 0 ; j < sfinfo.channels ; j++)
23+ audioOut[i] += audioIn[i*sfinfo.channels + j];
24+ audioOut[i] /= sfinfo.channels ;
2125 }
22- outFileInfo = inFileInfo;
23- outFileInfo.channels = 1 ;
26+ sf_close (sndfile);
27+ // write output
28+ int frames = sfinfo.frames ;
29+ sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16 ;
30+ sfinfo.channels = 1 ;
31+
2432 std::string outName;
2533 outName = path.substr (0 , path.length () - 4 );
2634 outName.append (" _mono.wav" );
27- SNDFILE *outFile = sf_open (outName. c_str (), SFM_WRITE , &outFileInfo);
28- if (outFile == nullptr ) {
29- sf_close (inFile);
30- sf_close (outFile );
31- delete[] inData ;
32- delete[] outData ;
35+
36+ sndfile = sf_open (outName. c_str (), SFM_WRITE , &sfinfo);
37+ if (sndfile == nullptr ) {
38+ sf_close (sndfile );
39+ delete[] audioIn ;
40+ delete[] audioOut ;
3341 throw FileNotCreatedException (outName);
3442 }
35- sf_writef_float (outFile, outData, inFileInfo. frames );
36- delete[] inData ;
37- delete[] outData;
38- sf_close (inFile) ;
39- sf_close (outFile) ;
43+ sf_write_float (sndfile, audioOut, frames);
44+ sf_close (sndfile) ;
45+ // free memory
46+ delete[] audioIn ;
47+ delete[] audioOut ;
4048}
0 commit comments