Skip to content

Instantly share code, notes, and snippets.

Created April 13, 2013 22:07
Show Gist options
  • Select an option

  • Save anonymous/5380279 to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/5380279 to your computer and use it in GitHub Desktop.
test
# wave_test.py
# python 2.7 doesn't support 'with' on the wave module
'''
original wave:
https://dl.dropboxusercontent.com/u/3397495/wav/we_must_build_upwards.wav
original label file, generated by audacity
https://dl.dropboxusercontent.com/u/3397495/wav/wmbu_labels
'''
import wave
import struct
filename = "we_must_build_upwards.wav"
info_filename = 'wmbu_labels'
def print_temp(a,b,c):
print('nseconds', a)
print('mark_start', b)
print('mark_end', c)
def get_sample_markers(info_filename):
'''read info file'''
def clean(i):
strs = i.split('\t')[:2]
return [float(i) for i in strs]
with open(info_filename) as f:
sample_markers = [clean(i) for i in f.readlines()]
return sample_markers
def get_duration_from_params(wave_params):
frate, nframes = wave_params[2:4]
duration_seconds = float(nframes)/float(frate)
print(frate, nframes, duration_seconds)
return duration_seconds
sample_markers = get_sample_markers(info_filename)
'''test on one marker'''
mark_start, mark_end = sample_markers[0]
nseconds = mark_end - mark_start
print_temp(nseconds, mark_start, mark_end)
'''read original file'''
f = wave.open(filename)
wave_params = f.getparams()
nchannels, sampwidth, frate, nframes, comptype, compname = wave_params
duration_seconds = get_duration_from_params(wave_params)
# find start frame, end frame and n (n samples)
start_frame = int(mark_start * frate)
end_frame = int(mark_end * frate)
n = end_frame - start_frame
print(start_frame, end_frame, n)
def generate_silence(duration):
'''duration in seconds, forces to be divisible by nchannels
assuming here nchannels is 2 - which is fine for my needs'''
dframes = int(frate*nchannels*duration)
return dframes if dframes%2 == 0 else drframes+1
f.setpos(start_frame)
data = f.readframes(n)
'''open destination for writing'''
wf = wave.open('destination.wav', 'wb')
wf.setparams(wave_params)
silent_frames = generate_silence(0)
silent_data = "".join((wave.struct.pack('h', 0) for i in range(silent_frames)))
wf.writeframes(silent_data)
wf.writeframes(data)
wf.close()
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment