-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwav_compressor.py
More file actions
60 lines (48 loc) · 1.44 KB
/
wav_compressor.py
File metadata and controls
60 lines (48 loc) · 1.44 KB
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
# Imports ---------------------------------------------------------------------------------------- #
from wav import WAV
import sys
# Functions -------------------------------------------------------------------------------------- #
# Source: http://rosettacode.org/wiki/LZW_compression#Python
def compress(uncompressed):
"""Compress a string to a list of output symbols."""
# Build the dictionary.
dict_size = 256
dictionary = {i.to_bytes(1, 'little'): i for i in range(dict_size)}
w: bytes = b""
result = []
for c in uncompressed:
c: bytes = c.to_bytes(1, 'little')
wc: bytes = w + c
if wc in dictionary:
w = wc
else:
result.append(dictionary[w])
# Add wc to the dictionary.
dictionary[wc] = dict_size
dict_size += 1
w = c
# Output the code for w.
if w:
result.append(dictionary[w])
return result
# Main ------------------------------------------------------------------------------------------- #
if __name__ == '__main__':
# Check args
if (len(sys.argv) != 2):
print('USAGE: python3 wav_compressor.py file_to_compress')
exit(1)
# Import
print('READING...')
wav = WAV(sys.argv[1])
# Compress
print('ENCODING...')
ih = wav.data_b
enc = compress(ih)
# Export
print('SAVING...')
comp_data = b''
wav.save_header('comp-output.wav', len(enc)*4)
with open('comp-output.wav', 'ab') as fh:
for i in enc:
fh.write(i.to_bytes(4, 'little'))
exit(0)