Skip to content

Instantly share code, notes, and snippets.

@jkmartindale
Last active October 28, 2019 20:00
Show Gist options
  • Save jkmartindale/c6093033bac8ab7e657ecf1d7f6dee0d to your computer and use it in GitHub Desktop.
Save jkmartindale/c6093033bac8ab7e657ecf1d7f6dee0d to your computer and use it in GitHub Desktop.
Tiny Python CLI to display the bit depth of a list of WAVs

bitdepth

Tiny Python CLI to display the bit depth of a list of WAVs. Pretty bad "by design", I'm only using this to quickly verify promotional files I get from my secret DJing career.

Usage

$ python bitdepth.py file1.wav file2.wav
file1.wav: 16-bit
file2.wav: 24-bit

Pass in a space-delimited list of files. Globs work too. If nothing is specified, bitdepth lists the bit depth of all WAV files in the current working directory.

import glob
import io
from itertools import chain
import struct
import sys
def find_bit_depth(file: io.BufferedReader) -> int:
if file.read(4) != b'RIFF':
print('Not a RIFF file', file=sys.stderr)
exit(-2)
file.read(4) # Length of file, minus the 4-byte RIFF marker
if file.read(4) != b'WAVE':
print('Not a WAVE file', file=sys.stderr)
exit(-3)
next_marker = file.read(4)
# JUNK chunk aligns the chunk offsets to some boundary, but doesn't always exist
if next_marker == b'JUNK':
file.read(struct.unpack('<L', file.read(4))[0])
# Read the format marker after reading the JUNK chunk
if file.read(4) != b'fmt ':
print('Misaligned fmt chunk', file=sys.stderr)
exit(-5)
# Ensure there's a format marker
elif next_marker != b'fmt ':
print('Misaligned fmt chunk', file=sys.stderr)
exit(-5)
file.read(4) # Chunk size
file.read(2) # Format code
file.read(2) # Number of interleaved channels
file.read(4) # Sampling rate
file.read(4) # Data rate
file.read(2) # Data block size
return struct.unpack('<H', file.read(2))[0]
if __name__ == '__main__':
# Add default behavior if no argument is specified
if len(sys.argv) == 1:
sys.argv.append('*.wav')
for filename in chain.from_iterable(glob.iglob(filename) for filename in sys.argv[1:]):
with open(filename, 'rb') as file:
print('%s: %d-bit' % (filename, find_bit_depth(file)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment