source: python/lib/aubio/slicing.py @ a88594d

feature/autosinkfeature/constantqfeature/pitchshiftfeature/pydocstringsfeature/timestretch
Last change on this file since a88594d was a88594d, checked in by Paul Brossier <piem@piem.org>, 21 months ago

[py] [slicing] add end of last region if missing

  • Property mode set to 100644
File size: 3.7 KB
Line 
1"""utility routines to slice sound files at given timestamps"""
2
3import os
4from aubio import source, sink
5
6_max_timestamp = 1e120
7
8def slice_source_at_stamps(source_file, timestamps, timestamps_end=None,
9                           output_dir=None, samplerate=0, hopsize=256):
10    """ slice a sound file at given timestamps """
11
12    if timestamps is None or len(timestamps) == 0:
13        raise ValueError("no timestamps given")
14
15    if timestamps[0] != 0:
16        timestamps = [0] + timestamps
17        if timestamps_end is not None:
18            timestamps_end = [timestamps[1] - 1] + timestamps_end
19
20    if timestamps_end is not None:
21        if len(timestamps_end) == len(timestamps) - 1:
22            timestamps_end = timestamps_end + [_max_timestamp]
23        elif len(timestamps_end) != len(timestamps):
24            raise ValueError("len(timestamps_end) != len(timestamps)")
25    else:
26        timestamps_end = [t - 1 for t in timestamps[1:]] + [_max_timestamp]
27
28    regions = list(zip(timestamps, timestamps_end))
29    #print regions
30
31    source_base_name, _ = os.path.splitext(os.path.basename(source_file))
32    if output_dir is not None:
33        if not os.path.isdir(output_dir):
34            os.makedirs(output_dir)
35        source_base_name = os.path.join(output_dir, source_base_name)
36
37    def new_sink_name(source_base_name, timestamp, samplerate):
38        """ create a sink based on a timestamp in samples, converted in seconds """
39        timestamp_seconds = timestamp / float(samplerate)
40        return source_base_name + "_%011.6f" % timestamp_seconds + '.wav'
41
42    # open source file
43    _source = source(source_file, samplerate, hopsize)
44    samplerate = _source.samplerate
45
46    total_frames = 0
47    slices = []
48
49    while True:
50        # get hopsize new samples from source
51        vec, read = _source.do_multi()
52        # if the total number of frames read will exceed the next region start
53        while len(regions) and total_frames + read >= regions[0][0]:
54            #print "getting", regions[0], "at", total_frames
55            # get next region
56            start_stamp, end_stamp = regions.pop(0)
57            # create a name for the sink
58            new_sink_path = new_sink_name(source_base_name, start_stamp, samplerate)
59            # create its sink
60            _sink = sink(new_sink_path, samplerate, _source.channels)
61            # create a dictionary containing all this
62            new_slice = {'start_stamp': start_stamp, 'end_stamp': end_stamp, 'sink': _sink}
63            # append the dictionary to the current list of slices
64            slices.append(new_slice)
65
66        for current_slice in slices:
67            start_stamp = current_slice['start_stamp']
68            end_stamp = current_slice['end_stamp']
69            _sink = current_slice['sink']
70            # sample index to start writing from new source vector
71            start = max(start_stamp - total_frames, 0)
72            # number of samples yet to written be until end of region
73            remaining = end_stamp - total_frames + 1
74            #print current_slice, remaining, start
75            # not enough frames remaining, time to split
76            if remaining < read:
77                if remaining > start:
78                    # write remaining samples from current region
79                    _sink.do_multi(vec[:, start:remaining], remaining - start)
80                    #print "closing region", "remaining", remaining
81                    # close this file
82                    _sink.close()
83            elif read > start:
84                # write all the samples
85                _sink.do_multi(vec[:, start:read], read - start)
86        total_frames += read
87        # remove old slices
88        slices = list(filter(lambda s: s['end_stamp'] > total_frames,
89            slices))
90        if read < hopsize:
91            break
Note: See TracBrowser for help on using the repository browser.