Created
December 10, 2019 19:11
-
-
Save Koasing/ab612eb95d7d1d21f1b66d4975dccc0c to your computer and use it in GitHub Desktop.
wave file lsb and msb histogram
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 wave | |
FILENAME = 'Eternal Snow_이용신_Returned Fullmoon.wav' | |
wav = wave.open(FILENAME, mode='rb') | |
n_channels, sample_width, frame_rate, no_frames, _, _ = wav.getparams() | |
sample_bits = sample_width * 8 | |
print(f'{FILENAME}') | |
print(f'{n_channels} channels, {frame_rate} kHz, {sample_bits} bits') | |
print(f'{no_frames / frame_rate:.3f} seconds long') | |
hist_left = [0] * (2**sample_bits) | |
hist_right = [0] * (2**sample_bits) | |
for i in range(no_frames): | |
if i % frame_rate == 0: | |
print(f'Processing {i}th frame ({i / no_frames * 100:.3f}%)...', end='\r') | |
# read sample data | |
d = wav.readframes(1) | |
l = int.from_bytes(d[:sample_width], byteorder='little', signed=True) | |
r = int.from_bytes(d[sample_width:], byteorder='little', signed=True) | |
# build histogram | |
hist_left[l] += 1 | |
hist_right[r] += 1 | |
for lsb_bits in range(1, 16): | |
bucket_size = 2 ** lsb_bits | |
bucket_left = [0] * bucket_size | |
bucket_right = [0] * bucket_size | |
for i in range(len(hist_left)): | |
bucket = i % bucket_size | |
bucket_left[bucket] += hist_left[i] | |
bucket_right[bucket] += hist_right[i] | |
with open(f'hist_lsb_{bucket_size}.txt', 'w') as fout: | |
for i in range(len(bucket_left)): | |
idx = i | |
if i >= bucket_size / 2: | |
idx = i - bucket_size | |
print(f'{idx}\t{bucket_left[i]}\t{bucket_right[i]}', file=fout) | |
for msb_bits in range(1, 16): | |
bucket_size = 2 ** msb_bits | |
filter_size = 2 ** (sample_bits - msb_bits) | |
bucket_left = [0] * bucket_size | |
bucket_right = [0] * bucket_size | |
for i in range(len(hist_left)): | |
bucket = i // filter_size | |
bucket_left[bucket] += hist_left[i] | |
bucket_right[bucket] += hist_right[i] | |
with open(f'hist_msb_{bucket_size}.txt', 'w') as fout: | |
for i in range(len(bucket_left)): | |
idx = i | |
if i >= bucket_size / 2: | |
idx = i - bucket_size | |
print(f'{idx}\t{bucket_left[i]}\t{bucket_right[i]}', file=fout) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment