source: python/lib/aubio/slicing.py @ 6f27719

feature/autosinkfeature/cnnfeature/cnn_orgfeature/constantqfeature/crepefeature/crepe_orgfeature/pitchshiftfeature/pydocstringsfeature/timestretchfix/ffmpeg5pitchshiftsamplertimestretchyinfft+
Last change on this file since 6f27719 was 6f27719, checked in by Paul Brossier <piem@piem.org>, 10 years ago

python/lib/aubio/slicing.py: improve slicing, make tests faster

  • Property mode set to 100644
File size: 2.2 KB
Line 
1from aubio import source, sink
2import os
3
4def slice_source_at_stamps(source_file, timestamps, timestamps_end = None,
5        output_dir = None,
6        samplerate = 0,
7        hopsize = 256):
8
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
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
40        if remaining < read:
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)
50            # write the remaining samples in the new file
51            g(vec[remaining:read], read - remaining)
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
61    # close the last file
62    del g
Note: See TracBrowser for help on using the repository browser.