Skip to content

Instantly share code, notes, and snippets.

@ains
Created September 17, 2016 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ains/cdfc5bc45feae7a84c7d86a83092a71f to your computer and use it in GitHub Desktop.
Save ains/cdfc5bc45feae7a84c7d86a83092a71f to your computer and use it in GitHub Desktop.
Python code to write FLAC mandatory headers for a stream (adapted from mutagen code)
import struct
from StringIO import StringIO
def write_flac_header(sample_rate, channels, bits_per_sample):
total_samples = 0
f = StringIO()
# write FLAC header
f.write("fLaC")
# write METADATA_BLOCK_HEADER(STREAMINFO)
f.write(chr(128))
f.write(struct.pack(">I", 34)[-3:])
# write METADATA_BLOCK(STREAMINFO)
f.write(struct.pack(">I", 4096)[-2:])
f.write(struct.pack(">I", 4096)[-2:])
f.write(struct.pack(">I", 0)[-3:])
f.write(struct.pack(">I", 0)[-3:])
# first 16 bits of sample rate
f.write(struct.pack(">I", sample_rate >> 4)[-2:])
# 4 bits sample, 3 channel, 1 bps
byte = (sample_rate & 0xF) << 4
byte += ((channels - 1) & 7) << 1
byte += ((bits_per_sample - 1) >> 4) & 1
f.write(chr(byte))
# 4 bits of bps, 4 of sample count
byte = ((bits_per_sample - 1) & 0xF) << 4
byte += (total_samples >> 32) & 0xF
f.write(chr(byte))
# last 32 of sample count
f.write(struct.pack(">I", 0 & 0xFFFFFFFFL))
# MD5 signature (unknown)
sig = 0
f.write(struct.pack(
">4I", (sig >> 96) & 0xFFFFFFFFL, (sig >> 64) & 0xFFFFFFFFL,
(sig >> 32) & 0xFFFFFFFFL, sig & 0xFFFFFFFFL))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment