Skip to content

Instantly share code, notes, and snippets.

@whoeverest
Created July 6, 2012 19:40
Show Gist options
  • Save whoeverest/3062336 to your computer and use it in GitHub Desktop.
Save whoeverest/3062336 to your computer and use it in GitHub Desktop.
Pulses from .wav
import wave
import sys
if len(sys.argv) > 2:
path = sys.argv[1]
else:
path = "/home/whoeverest/code/klima-reverse/16c.wav"
wav = wave.open(path)
frames = map(ord, wav.readframes(wav.getnframes()))
# Merge frames in pairs: frame[0] * frame[1], frame[2] * frame[3] etc.
frames = [frames[i] * frames[i+1] for i in range(0, len(frames), 2)]
# Normalize: 1 if above half strength, 0 if under.
half_strength = max(frames) / 2
frames = [1 if frame > half_strength else 0 for frame in frames]
# Detect changes: from 1 -> 0 or from 0 -> 1.
changes = [i for i in range(len(frames) - 2) if frames[i] != frames[i+1]]
def find_pulses(changes, threshold=47, start=0):
level = start
sequence = []
for i in range(len(changes)):
if i == len(changes) - 2:
break
if changes[i+1] - changes[i] > threshold:
# Pulse: (level, start, end)
sequence.append((level, changes[i], changes[i+1]))
level = 1 if not level else 0
return sequence
# We don't know the threshold, so try out different
# values and see if we can spot a pattern.
start, end = 45, 50
sequences = [find_pulses(changes, thr) for thr in range(start, end)]
for seq in sequences:
print seq
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment