1 from aubio import source, sink
6 def slice_source_at_stamps(source_file, timestamps, timestamps_end = None,
11 if timestamps == None or len(timestamps) == 0:
12 raise ValueError ("no timestamps given")
14 if timestamps[0] != 0:
15 timestamps = [0] + timestamps
17 if timestamps_end != None:
18 if len(timestamps_end) != len(timestamps):
19 raise ValueError ("len(timestamps_end) != len(timestamps)")
21 timestamps_end = [t - 1 for t in timestamps[1:] ] + [ max_timestamp ]
23 regions = zip(timestamps, timestamps_end)
26 source_base_name, source_ext = os.path.splitext(os.path.basename(source_file))
27 if output_dir != None:
28 if not os.path.isdir(output_dir):
29 os.makedirs(output_dir)
30 source_base_name = os.path.join(output_dir, source_base_name)
32 def new_sink_name(source_base_name, timestamp, samplerate):
33 timestamp_seconds = timestamp / float(samplerate)
34 #print source_base_name + '_%02.3f' % (timestamp_seconds) + '.wav'
35 return source_base_name + '_%02.3f' % (timestamp_seconds) + '.wav'
38 s = source(source_file, samplerate, hopsize)
39 samplerate = s.get_samplerate()
45 # get hopsize new samples from source
47 # if the total number of frames read will exceed the next region start
48 if len(regions) and total_frames + read >= regions[0][0]:
49 #print "getting", regions[0], "at", total_frames
51 start_stamp, end_stamp = regions.pop(0)
52 # create a name for the sink
53 new_sink_path = new_sink_name(source_base_name, start_stamp, samplerate)
55 g = sink(new_sink_path, samplerate)
56 # create a dictionary containing all this
57 new_slice = {'start_stamp': start_stamp, 'end_stamp': end_stamp, 'sink': g}
58 # append the dictionary to the current list of slices
59 slices.append(new_slice)
61 for current_slice in slices:
62 start_stamp = current_slice['start_stamp']
63 end_stamp = current_slice['end_stamp']
64 g = current_slice['sink']
65 # sample index to start writing from new source vector
66 start = max(start_stamp - total_frames, 0)
67 # number of samples yet to written be until end of region
68 remaining = end_stamp - total_frames + 1
69 #print current_slice, remaining, start
70 # not enough frames remaining, time to split
73 # write remaining samples from current region
74 g(vec[start:remaining], remaining - start)
75 #print "closing region", "remaining", remaining
79 # write all the samples
80 g(vec[start:read], read - start)
82 if read < hopsize: break