From 264247e4d3705ec628448d0ebeb1268e4090b2a7 Mon Sep 17 00:00:00 2001 From: Paul Brossier Date: Fri, 8 Mar 2013 07:41:48 -0500 Subject: [PATCH] demos/demo_slicing.py: slice exactly at region boundary --- python/demos/demo_slicing.py | 46 ++++++++++++++++++++++++++---------- 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/python/demos/demo_slicing.py b/python/demos/demo_slicing.py index 3f2e2d28..a21252ad 100755 --- a/python/demos/demo_slicing.py +++ b/python/demos/demo_slicing.py @@ -10,19 +10,41 @@ if __name__ == '__main__': sys.exit(1) source_file = sys.argv[1] duration = float(sys.argv[2]) - sink_base, sink_ext = os.path.splitext(os.path.basename(source_file)) - slice_n, total_frames, read = 1, 0, 256 - f = source(source_file, 0, 256) - g = sink(sink_base + '-%02d' % slice_n + sink_ext, f.samplerate) - while read: + source_base_name, source_ext = os.path.splitext(os.path.basename(source_file)) + + hopsize = 256 + slice_n, total_frames_written, read = 0, 0, hopsize + + def new_sink_name(source_base_name, slice_n, duration = duration): + return source_base_name + '_%02.3f' % (slice_n*duration) + '.wav' + + f = source(source_file, 0, hopsize) + samplerate = f.samplerate + g = sink(new_sink_name(source_base_name, slice_n), samplerate) + + #print "new slice:", slice_n, 0, "+", 0, "=", 0 + while read == hopsize: vec, read = f() - g(vec, read) - total_frames += read - if total_frames / float(f.samplerate) >= duration * slice_n: - slice_n += 1 + start_of_next_region = int(duration * samplerate * (slice_n + 1)) + remaining = start_of_next_region - total_frames_written + # number of samples remaining is less than what we got + if remaining <= read: + # write remaining samples from current region + g(vec[0:remaining], remaining) + # close this file del g - g = sink(sink_base + '-%02d' % slice_n + sink_ext, f.samplerate) - total_duration = total_frames / float(f.samplerate) - print 'created %(slice_n)d slices from %(source_file)s' % locals(), + #print "new slice", slice_n, total_frames_written, "+", remaining, "=", start_of_next_region + slice_n += 1 + # create a new file for the new region + g = sink(new_sink_name(source_base_name, slice_n), samplerate) + # write the remaining samples in the new file + g(vec[remaining:read], read - remaining) + else: + g(vec[0:read], read) + total_frames_written += read + total_duration = total_frames_written / float(samplerate) + slice_n += 1 + print 'created %(slice_n)s slices from %(source_base_name)s%(source_ext)s' % locals(), print ' (total duration %(total_duration).2fs)' % locals() + # close source and sink files del f, g -- 2.26.2