1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_WAVEWRITER_H_
18
19#define ANDROID_WAVEWRITER_H_
20
21namespace android {
22
23class WaveWriter {
24public:
25    WaveWriter(const char *filename,
26               uint16_t num_channels, uint32_t sampling_rate)
27        : mFile(fopen(filename, "wb")),
28          mTotalBytes(0) {
29        fwrite("RIFFxxxxWAVEfmt \x10\x00\x00\x00\x01\x00", 1, 22, mFile);
30        write_u16(num_channels);
31        write_u32(sampling_rate);
32        write_u32(sampling_rate * num_channels * 2);
33        write_u16(num_channels * 2);
34        write_u16(16);
35        fwrite("dataxxxx", 1, 8, mFile);
36    }
37
38    ~WaveWriter() {
39        fseek(mFile, 40, SEEK_SET);
40        write_u32(mTotalBytes);
41
42        fseek(mFile, 4, SEEK_SET);
43        write_u32(36 + mTotalBytes);
44
45        fclose(mFile);
46        mFile = NULL;
47    }
48
49    void Append(const void *data, size_t size) {
50        fwrite(data, 1, size, mFile);
51        mTotalBytes += size;
52    }
53
54private:
55    void write_u16(uint16_t x) {
56        fputc(x & 0xff, mFile);
57        fputc(x >> 8, mFile);
58    }
59
60    void write_u32(uint32_t x) {
61        write_u16(x & 0xffff);
62        write_u16(x >> 16);
63    }
64
65    FILE *mFile;
66    size_t mTotalBytes;
67};
68
69}  // namespace android
70
71#endif  // ANDROID_WAVEWRITER_H_
72