Created
June 8, 2022 19:07
-
-
Save timrprobocom/37bfe560bfa27ab661238f3bdfa317e6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import struct | |
# Return a RIFF file | |
class LIST: | |
def __init__(self, name, f): | |
# contains a type and a list of subchunks. | |
self.offset = f.tell() - 4 | |
self.name = name.decode() | |
size = struct.unpack('I', f.read(4))[0] | |
self.ctype = f.read(4).decode() | |
self.sub = [] | |
# recursive fill chunks | |
while f.tell() < self.offset + size: | |
name = f.read(4) | |
if name in (b'RIFF',b'LIST'): | |
self.sub.append( LIST( name, f ) ) | |
else: | |
self.sub.append( CHUNK( name, f ) ) | |
def __repr__(self): | |
r = f'<LIST {self.name}/{self.ctype} with {len(self.sub)} chunks>\n' | |
for s in self.sub: | |
r += f' {s}\n' | |
return r | |
def size(self): | |
return 4 + sum(8 + s.size() for s in self.sub) | |
def write( self, f ): | |
f.write( self.name.encode() ) | |
f.write( struct.pack('I', self.size() ) ) | |
f.write( self.ctype.encode() ) | |
for s in self.sub: | |
s.write( f ) | |
class CHUNK: | |
def __init__(self, name, f): | |
self.name = name.decode() | |
size = struct.unpack('I', f.read(4))[0] | |
self.data = f.read(size) | |
def __repr__(self): | |
return f'<CHUNK {self.name} with {len(self.data)} bytes>' | |
def set_data( self, data ): | |
self.data = data | |
if len(data) % 2: | |
self.data += b'\x00' | |
def size(self): | |
return len(self.data) | |
def write(self, f): | |
f.write( self.name.encode() ) | |
f.write( struct.pack('I', len(self.data)) ) | |
f.write( self.data ) | |
def dump(tree, nest=0): | |
tab = ' '*nest | |
if isinstance(tree,LIST): | |
print( tab+'LIST', tree.name, tree.ctype, 'contains', len(tree.sub), 'chunks' ) | |
for s in tree.sub: | |
dump( s, nest+1 ) | |
else: | |
print( tab+'CHUNK', tree.name, 'contains', len(tree.data), 'bytes') | |
def test(): | |
# Read the whole file. | |
f = open('/dev/CueManager/Whistle.wav','rb') | |
name = f.read(4) | |
assert name == b'RIFF' | |
tree = LIST(name, f) | |
dump(tree) | |
print(tree.sub[1].sub[0].data) | |
print(tree.size()) | |
# Change the info chunk. | |
tree.sub[1].sub[0].set_data( b"New Info\x00" ) | |
print(tree.size()) | |
tree.write( open('xxx.wav','wb') ) | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you! I'm from the stackoverflow question, by the way. Another question, what is the licensing of this code?