Initial import
[wav_header.git] / wav_header.py
1 #!/usr/bin/env python
2 #
3 # wav_header - write the header of a wav file
4 #
5 # Copyright (C) 2010  Antonio Ospite <ospite@studenti.unina.it>
6 #
7 # This program is free software. It comes without any warranty, to
8 # the extent permitted by applicable law. You can redistribute it
9 # and/or modify it under the terms of the Do What The Fuck You Want
10 # To Public License, Version 2, as published by Sam Hocevar. See
11 # http://sam.zoy.org/wtfpl/COPYING for more details.
12
13 import sys
14 import struct
15
16 def hexstring_to_bytes(hex_string):
17     res = ""
18     for i in range(0, len(hex_string), 2):
19             res += chr(int(hex_string[i:i+2], 16))
20
21     return res
22
23 def write_wav_header(out_file, fmt, codec_private_data, data_len):
24
25     extradata = hexstring_to_bytes(codec_private_data)
26
27     fmt['cbSize'] = len(extradata)
28     fmt_len = 18 + fmt['cbSize']
29     wave_len = len("WAVEfmt ") + 4 + fmt_len + len('data') + 4
30
31     out_file.write("RIFF")
32     out_file.write(struct.pack('<L', wave_len))
33     out_file.write("WAVEfmt ")
34     out_file.write(struct.pack('<L', fmt_len))
35     out_file.write(struct.pack('<H', fmt['wFormatTag']))
36     out_file.write(struct.pack('<H', fmt['nChannels']))
37     out_file.write(struct.pack('<L', fmt['nSamplesPerSec']))
38     out_file.write(struct.pack('<L', fmt['nAvgBytesPerSec']))
39     out_file.write(struct.pack('<H', fmt['nBlockAlign']))
40     out_file.write(struct.pack('<H', fmt['wBitsPerSample']))
41     out_file.write(struct.pack('<H', fmt['cbSize']))
42     out_file.write(extradata)
43     out_file.write("data")
44     out_file.write(struct.pack('<L', data_len))
45
46 if __name__ == "__main__":
47
48     codec_private_data = "008800000f0000000000"
49
50     fmt = {}
51     fmt['wFormatTag'] = 0x161
52     fmt['nChannels'] = 2
53     fmt['nSamplesPerSec'] = 48000
54     fmt['nAvgBytesPerSec'] = 192000 / 8
55     fmt['wBitsPerSample'] = 16
56     fmt['nBlockAlign'] = 8192
57     fmt['cbSize'] = 0
58
59     data_len = 70680576
60
61     write_wav_header(sys.stdout, fmt, codec_private_data, data_len)