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