Created
October 14, 2010 15:52
-
-
Save engie/626434 to your computer and use it in GitHub Desktop.
This file contains 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 | |
import sys | |
class NamedStruct( struct.Struct ): | |
def __init__(self, *contents): | |
""" | |
Construct with ("Format", "Name"), tuples as arguments. | |
""" | |
self.names, format = zip(*contents) | |
#Flatten format into a string | |
format = "".join( format ) | |
struct.Struct.__init__( self, format ) | |
def unpack( self, str ): | |
return dict( zip( self.names, struct.Struct.unpack( self, str ) ) ) | |
wav_file_header = NamedStruct( ("4c", id), # should always contain "RIFF" | |
("i", totallength), # total file length minus 8 | |
("8c", wavefmt), # should be "WAVEfmt " | |
("i", format), # 16 for PCM format | |
("h", cm), # 1 for PCM format | |
("h", channels), # channels | |
("i", requency), # sampling frequency | |
("i", bytes_per_second), | |
("h", bytes_by_capture), | |
("h", bits_per_sample), | |
("4c", data[4]), # should always contain "data" | |
("i", bytes_in_data) ) | |
filename = sys.argv[1] | |
try: | |
wav = open( filename, "rb" ) | |
except IOError: | |
print "Can't open input file %s" % filename | |
sys.exit(-1) | |
try: | |
header = wav_file_header.unpack( wav.read( wav_file_header.size ) ) | |
except IOError: | |
print "Can't read file header" | |
sys.exit(-1) | |
if header["id"] != "RIFF": | |
print "ERROR: Not wav format" | |
sys.exit(-1) | |
sum = 0 | |
value_unpacker = struct.Struct("h") | |
while True: | |
try: | |
value = value_unpacker.unpack( wav.read(value_unpacker.size) ) | |
except IOError: | |
break | |
sum += abs( value ) | |
print sum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Assume correct endianness to match C code, otherwise lob a couple of < or > into the struct definitions.