1 /*
2 Copyright (C) 2006 Nasca Octavian Paul
3 Author: Nasca Octavian Paul
4 Mark McCurry
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License (version 2) for more details.
15
16 You should have received a copy of the GNU General Public License (version 2)
17 along with this program; if not, write to the Free Software Foundation,
18 Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20
21 #include <cstdio>
22 #include <cstring>
23 #include <cstdlib>
24 #include <iostream>
25 #include "WavFile.h"
26 using namespace std;
27
WavFile(string filename,int samplerate,int channels)28 WavFile::WavFile(string filename, int samplerate, int channels)
29 :sampleswritten(0), samplerate(samplerate), channels(channels),
30 file(fopen(filename.c_str(), "w"))
31
32 {
33 if(file) {
34 cout << "INFO: Making space for wave file header" << endl;
35 //making space for the header written at destruction
36 char tmp[44];
37 memset(tmp, 0, 44 * sizeof(char));
38 fwrite(tmp, 1, 44, file);
39 }
40 }
41
~WavFile()42 WavFile::~WavFile()
43 {
44 if(file) {
45 cout << "INFO: Writing wave file header" << endl;
46
47 unsigned int chunksize;
48 rewind(file);
49
50 fwrite("RIFF", 4, 1, file);
51 chunksize = sampleswritten * 4 + 36;
52 fwrite(&chunksize, 4, 1, file);
53
54 fwrite("WAVEfmt ", 8, 1, file);
55 chunksize = 16;
56 fwrite(&chunksize, 4, 1, file);
57 unsigned short int formattag = 1; //uncompresed wave
58 fwrite(&formattag, 2, 1, file);
59 unsigned short int nchannels = channels; //stereo
60 fwrite(&nchannels, 2, 1, file);
61 unsigned int samplerate_ = samplerate; //samplerate
62 fwrite(&samplerate_, 4, 1, file);
63 unsigned int bytespersec = samplerate * 2 * channels; //bytes/sec
64 fwrite(&bytespersec, 4, 1, file);
65 unsigned short int blockalign = 2 * channels; //2 channels * 16 bits/8
66 fwrite(&blockalign, 2, 1, file);
67 unsigned short int bitspersample = 16;
68 fwrite(&bitspersample, 2, 1, file);
69
70 fwrite("data", 4, 1, file);
71 chunksize = sampleswritten * blockalign;
72 fwrite(&chunksize, 4, 1, file);
73
74 fclose(file);
75 file = NULL;
76 }
77 }
78
good() const79 bool WavFile::good() const
80 {
81 return file;
82 }
83
writeStereoSamples(int nsmps,short int * smps)84 void WavFile::writeStereoSamples(int nsmps, short int *smps)
85 {
86 if(file) {
87 fwrite(smps, nsmps, 4, file);
88 sampleswritten += nsmps;
89 }
90 }
91
writeMonoSamples(int nsmps,short int * smps)92 void WavFile::writeMonoSamples(int nsmps, short int *smps)
93 {
94 if(file) {
95 fwrite(smps, nsmps, 2, file);
96 sampleswritten += nsmps;
97 }
98 }
99