[88432a9] | 1 | from aubio import source, sink |
---|
| 2 | import os |
---|
| 3 | |
---|
| 4 | def slice_source_at_stamps(source_file, timestamps, timestamps_end = None, |
---|
| 5 | output_dir = None, |
---|
| 6 | samplerate = 0, |
---|
| 7 | hopsize = 256): |
---|
| 8 | |
---|
[aee840b] | 9 | if timestamps == None or len(timestamps) == 0: |
---|
| 10 | raise ValueError ("no timestamps given") |
---|
| 11 | |
---|
| 12 | if timestamps_end != None and len(timestamps_end) != len(timestamps): |
---|
| 13 | raise ValueError ("len(timestamps_end) != len(timestamps)") |
---|
| 14 | |
---|
[88432a9] | 15 | source_base_name, source_ext = os.path.splitext(os.path.basename(source_file)) |
---|
| 16 | if output_dir != None: |
---|
| 17 | if not os.path.isdir(output_dir): |
---|
| 18 | os.makedirs(output_dir) |
---|
| 19 | source_base_name = os.path.join(output_dir, source_base_name) |
---|
| 20 | |
---|
| 21 | def new_sink_name(source_base_name, timestamp): |
---|
| 22 | return source_base_name + '_%02.3f' % (timestamp) + '.wav' |
---|
| 23 | |
---|
| 24 | # reopen source file |
---|
| 25 | s = source(source_file, samplerate, hopsize) |
---|
| 26 | if samplerate == 0: samplerate = s.get_samplerate() |
---|
| 27 | # create first sink at 0 |
---|
| 28 | g = sink(new_sink_name(source_base_name, 0.), samplerate) |
---|
| 29 | total_frames = 0 |
---|
| 30 | # get next region |
---|
| 31 | next_stamp = int(timestamps.pop(0)) |
---|
| 32 | if not next_stamp: |
---|
| 33 | next_stamp = int(timestamps.pop(0)) |
---|
| 34 | |
---|
| 35 | while True: |
---|
| 36 | # get hopsize new samples from source |
---|
| 37 | vec, read = s() |
---|
| 38 | remaining = next_stamp - total_frames |
---|
| 39 | # not enough frames remaining, time to split |
---|
[6f27719] | 40 | if remaining < read: |
---|
[88432a9] | 41 | if remaining != 0: |
---|
| 42 | # write remaining samples from current region |
---|
| 43 | g(vec[0:remaining], remaining) |
---|
| 44 | # close this file |
---|
| 45 | del g |
---|
| 46 | # create a new file for the new region |
---|
| 47 | new_sink_path = new_sink_name(source_base_name, next_stamp / float(samplerate)) |
---|
| 48 | #print "new slice", total_frames, "+", remaining, "=", next_stamp |
---|
| 49 | g = sink(new_sink_path, samplerate) |
---|
[6f27719] | 50 | # write the remaining samples in the new file |
---|
| 51 | g(vec[remaining:read], read - remaining) |
---|
[88432a9] | 52 | if len(timestamps): |
---|
| 53 | next_stamp = int(timestamps.pop(0)) |
---|
| 54 | else: |
---|
| 55 | next_stamp = 1e120 |
---|
| 56 | else: |
---|
| 57 | g(vec[0:read], read) |
---|
| 58 | total_frames += read |
---|
| 59 | if read < hopsize: break |
---|
| 60 | |
---|
[6f27719] | 61 | # close the last file |
---|
[88432a9] | 62 | del g |
---|