File: wav.cpp

package info (click to toggle)
opencore-amr 0.1.2-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 6,188 kB
  • ctags: 2,243
  • sloc: cpp: 35,778; sh: 10,133; makefile: 297; ansic: 73
file content (87 lines) | stat: -rw-r--r-- 2,326 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/* ------------------------------------------------------------------
 * Copyright (C) 2009 Martin Storsjo
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 * -------------------------------------------------------------------
 */

#include "wav.h"

void WavWriter::writeString(const char *str) {
	fputc(str[0], wav);
	fputc(str[1], wav);
	fputc(str[2], wav);
	fputc(str[3], wav);
}

void WavWriter::writeInt32(int value) {
	fputc((value >>  0) & 0xff, wav);
	fputc((value >>  8) & 0xff, wav);
	fputc((value >> 16) & 0xff, wav);
	fputc((value >> 24) & 0xff, wav);
}

void WavWriter::writeInt16(int value) {
	fputc((value >> 0) & 0xff, wav);
	fputc((value >> 8) & 0xff, wav);
}

void WavWriter::writeHeader(int length) {
	writeString("RIFF");
	writeInt32(4 + 8 + 16 + 8 + length);
	writeString("WAVE");

	writeString("fmt ");
	writeInt32(16);

	int bytesPerFrame = bitsPerSample/8*channels;
	int bytesPerSec = bytesPerFrame*sampleRate;
	writeInt16(1);             // Format
	writeInt16(channels);      // Channels
	writeInt32(sampleRate);    // Samplerate
	writeInt32(bytesPerSec);   // Bytes per sec
	writeInt16(bytesPerFrame); // Bytes per frame
	writeInt16(bitsPerSample); // Bits per sample

	writeString("data");
	writeInt32(length);
}

WavWriter::WavWriter(const char *filename, int sampleRate, int bitsPerSample, int channels) {
	wav = fopen(filename, "wb");
	if (wav == NULL)
		return;
	dataLength = 0;
	this->sampleRate = sampleRate;
	this->bitsPerSample = bitsPerSample;
	this->channels = channels;

	writeHeader(dataLength);
}

WavWriter::~WavWriter() {
	if (wav == NULL)
		return;
	fseek(wav, 0, SEEK_SET);
	writeHeader(dataLength);
	fclose(wav);
}

void WavWriter::writeData(const unsigned char* data, int length) {
	if (wav == NULL)
		return;
	fwrite(data, length, 1, wav);
	dataLength += length;
}