demos/demo_slicing.py: slice exactly at region boundary
authorPaul Brossier <piem@piem.org>
Fri, 8 Mar 2013 12:41:48 +0000 (07:41 -0500)
committerPaul Brossier <piem@piem.org>
Fri, 8 Mar 2013 12:41:48 +0000 (07:41 -0500)
python/demos/demo_slicing.py

index 3f2e2d288e5d5626b73b2f80bba41c9362571319..a21252ad6019b8015d6f3f65d5639366d3d14c2b 100755 (executable)
@@ -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