WavFile.cpp (2569B)
1 /* 2 ZynAddSubFX - a software synthesizer 3 4 WavFile.cpp - Wav File Serialization 5 Copyright (C) 2006 Nasca Octavian Paul 6 Author: Nasca Octavian Paul 7 Mark McCurry 8 9 This program is free software; you can redistribute it and/or 10 modify it under the terms of the GNU General Public License 11 as published by the Free Software Foundation; either version 2 12 of the License, or (at your option) any later version. 13 */ 14 15 #include <cstdio> 16 #include <cstring> 17 #include <cstdlib> 18 #include <iostream> 19 #include "WavFile.h" 20 using namespace std; 21 22 namespace zyn { 23 24 WavFile::WavFile(string filename, int samplerate, int channels) 25 :sampleswritten(0), samplerate(samplerate), channels(channels), 26 file(fopen(filename.c_str(), "w")) 27 28 { 29 if(file) { 30 cout << "INFO: Making space for wave file header" << endl; 31 //making space for the header written at destruction 32 char tmp[44]; 33 memset(tmp, 0, 44 * sizeof(char)); 34 fwrite(tmp, 1, 44, file); 35 } 36 } 37 38 WavFile::~WavFile() 39 { 40 if(file) { 41 cout << "INFO: Writing wave file header" << endl; 42 43 unsigned int chunksize; 44 rewind(file); 45 46 fwrite("RIFF", 4, 1, file); 47 chunksize = sampleswritten * 4 + 36; 48 fwrite(&chunksize, 4, 1, file); 49 50 fwrite("WAVEfmt ", 8, 1, file); 51 chunksize = 16; 52 fwrite(&chunksize, 4, 1, file); 53 unsigned short int formattag = 1; //uncompressed wave 54 fwrite(&formattag, 2, 1, file); 55 unsigned short int nchannels = channels; //stereo 56 fwrite(&nchannels, 2, 1, file); 57 unsigned int samplerate_ = samplerate; //samplerate 58 fwrite(&samplerate_, 4, 1, file); 59 unsigned int bytespersec = samplerate * 2 * channels; //bytes/sec 60 fwrite(&bytespersec, 4, 1, file); 61 unsigned short int blockalign = 2 * channels; //2 channels * 16 bits/8 62 fwrite(&blockalign, 2, 1, file); 63 unsigned short int bitspersample = 16; 64 fwrite(&bitspersample, 2, 1, file); 65 66 fwrite("data", 4, 1, file); 67 chunksize = sampleswritten * blockalign; 68 fwrite(&chunksize, 4, 1, file); 69 70 fclose(file); 71 file = NULL; 72 } 73 } 74 75 bool WavFile::good() const 76 { 77 return file; 78 } 79 80 void WavFile::writeStereoSamples(int nsmps, short int *smps) 81 { 82 if(file) { 83 fwrite(smps, nsmps, 4, file); 84 sampleswritten += nsmps; 85 } 86 } 87 88 void WavFile::writeMonoSamples(int nsmps, short int *smps) 89 { 90 if(file) { 91 fwrite(smps, nsmps, 2, file); 92 sampleswritten += nsmps; 93 } 94 } 95 96 }