Skip to content

Instantly share code, notes, and snippets.

Created April 13, 2013 20:46
Show Gist options
  • Select an option

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

Select an option

Save anonymous/5380009 to your computer and use it in GitHub Desktop.
test
# wave_test.py
# python 2.7 doesn't support 'with' on the wave module
import wave
import struct
filename = "snipped.wav"
info_filename = 'snipped_info'
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)
f.setpos(start_frame)
data = f.readframes(n)
'''open destination for writing'''
wf = wave.open('destination.wav', 'wb')
wf.setparams(wave_params)
silent_frames = frate*nchannels*2 # 2 seconds
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