[c11c549] | 1 | #! /usr/bin/env python |
---|
| 2 | |
---|
| 3 | import sys |
---|
| 4 | import os.path |
---|
| 5 | from aubio import source, sink |
---|
| 6 | |
---|
| 7 | if __name__ == '__main__': |
---|
| 8 | if len(sys.argv) < 3: |
---|
[4120fbc] | 9 | print('usage: %s <inputfile> <duration>' % sys.argv[0]) |
---|
[c11c549] | 10 | sys.exit(1) |
---|
| 11 | source_file = sys.argv[1] |
---|
| 12 | duration = float(sys.argv[2]) |
---|
[264247e] | 13 | source_base_name, source_ext = os.path.splitext(os.path.basename(source_file)) |
---|
| 14 | |
---|
| 15 | hopsize = 256 |
---|
| 16 | slice_n, total_frames_written, read = 0, 0, hopsize |
---|
| 17 | |
---|
| 18 | def new_sink_name(source_base_name, slice_n, duration = duration): |
---|
| 19 | return source_base_name + '_%02.3f' % (slice_n*duration) + '.wav' |
---|
| 20 | |
---|
| 21 | f = source(source_file, 0, hopsize) |
---|
| 22 | samplerate = f.samplerate |
---|
| 23 | g = sink(new_sink_name(source_base_name, slice_n), samplerate) |
---|
| 24 | |
---|
| 25 | #print "new slice:", slice_n, 0, "+", 0, "=", 0 |
---|
| 26 | while read == hopsize: |
---|
[c11c549] | 27 | vec, read = f() |
---|
[264247e] | 28 | start_of_next_region = int(duration * samplerate * (slice_n + 1)) |
---|
| 29 | remaining = start_of_next_region - total_frames_written |
---|
| 30 | # number of samples remaining is less than what we got |
---|
| 31 | if remaining <= read: |
---|
| 32 | # write remaining samples from current region |
---|
| 33 | g(vec[0:remaining], remaining) |
---|
| 34 | # close this file |
---|
[c11c549] | 35 | del g |
---|
[264247e] | 36 | #print "new slice", slice_n, total_frames_written, "+", remaining, "=", start_of_next_region |
---|
| 37 | slice_n += 1 |
---|
| 38 | # create a new file for the new region |
---|
| 39 | g = sink(new_sink_name(source_base_name, slice_n), samplerate) |
---|
| 40 | # write the remaining samples in the new file |
---|
| 41 | g(vec[remaining:read], read - remaining) |
---|
| 42 | else: |
---|
| 43 | g(vec[0:read], read) |
---|
| 44 | total_frames_written += read |
---|
| 45 | total_duration = total_frames_written / float(samplerate) |
---|
| 46 | slice_n += 1 |
---|
[4120fbc] | 47 | outstr = 'created %(slice_n)s slices from %(source_base_name)s%(source_ext)s' % locals() |
---|
| 48 | outstr += ' (total duration %(total_duration).2fs)' % locals() |
---|
| 49 | print(outstr) |
---|
[264247e] | 50 | # close source and sink files |
---|
[c11c549] | 51 | del f, g |
---|