source: python/lib/aubio/cut.py @ f8c75aa

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

[py] [style] add space after , in cut.py

  • Property mode set to 100644
File size: 7.2 KB
Line 
1#! /usr/bin/env python
2
3""" this file was written by Paul Brossier
4  it is released under the GNU/GPL license.
5"""
6
7import sys
8import warnings
9from aubio.cmd import AubioArgumentParser
10from aubio.slicing import slice_source_at_stamps
11
12
13def aubio_cut_parser():
14    parser = AubioArgumentParser()
15    parser.add_input()
16    parser.add_argument("-O", "--onset-method",
17            action="store", dest="onset_method", default='default',
18            metavar = "<onset_method>",
19            help="onset detection method [default=default] \
20                    complexdomain|hfc|phase|specdiff|energy|kl|mkl")
21    # cutting methods
22    parser.add_argument("-b", "--beat",
23            action="store_true", dest="beat", default=False,
24            help="slice at beat locations")
25    """
26    parser.add_argument("-S", "--silencecut",
27            action="store_true", dest="silencecut", default=False,
28            help="use silence locations")
29    parser.add_argument("-s", "--silence",
30            metavar = "<value>",
31            action="store", dest="silence", default=-70,
32            help="silence threshold [default=-70]")
33            """
34    # algorithm parameters
35    parser.add_buf_hop_size()
36    parser.add_argument("-t", "--threshold", "--onset-threshold",
37            metavar = "<threshold>", type=float,
38            action="store", dest="threshold", default=0.3,
39            help="onset peak picking threshold [default=0.3]")
40    parser.add_argument("-c", "--cut",
41            action="store_true", dest="cut", default=False,
42            help="cut input sound file at detected labels")
43    parser.add_minioi()
44
45    """
46    parser.add_argument("-D", "--delay",
47            action = "store", dest = "delay", type = float,
48            metavar = "<seconds>", default=0,
49            help="number of seconds to take back [default=system]\
50                    default system delay is 3*hopsize/samplerate")
51    parser.add_argument("-C", "--dcthreshold",
52            metavar = "<value>",
53            action="store", dest="dcthreshold", default=1.,
54            help="onset peak picking DC component [default=1.]")
55    parser.add_argument("-L", "--localmin",
56            action="store_true", dest="localmin", default=False,
57            help="use local minima after peak detection")
58    parser.add_argument("-d", "--derivate",
59            action="store_true", dest="derivate", default=False,
60            help="derivate onset detection function")
61    parser.add_argument("-z", "--zerocross",
62            metavar = "<value>",
63            action="store", dest="zerothres", default=0.008,
64            help="zero-crossing threshold for slicing [default=0.00008]")
65    # plotting functions
66    parser.add_argument("-p", "--plot",
67            action="store_true", dest="plot", default=False,
68            help="draw plot")
69    parser.add_argument("-x", "--xsize",
70            metavar = "<size>",
71            action="store", dest="xsize", default=1.,
72            type=float, help="define xsize for plot")
73    parser.add_argument("-y", "--ysize",
74            metavar = "<size>",
75            action="store", dest="ysize", default=1.,
76            type=float, help="define ysize for plot")
77    parser.add_argument("-f", "--function",
78            action="store_true", dest="func", default=False,
79            help="print detection function")
80    parser.add_argument("-n", "--no-onsets",
81            action="store_true", dest="nplot", default=False,
82            help="do not plot detected onsets")
83    parser.add_argument("-O", "--outplot",
84            metavar = "<output_image>",
85            action="store", dest="outplot", default=None,
86            help="save plot to output.{ps,png}")
87    parser.add_argument("-F", "--spectrogram",
88            action="store_true", dest="spectro", default=False,
89            help="add spectrogram to the plot")
90    """
91    parser.add_slicer_options()
92    parser.add_verbose_help()
93    return parser
94
95
96def _cut_analyze(options):
97    hopsize = options.hop_size
98    bufsize = options.buf_size
99    samplerate = options.samplerate
100    source_uri = options.source_uri
101
102    # analyze pass
103    from aubio import onset, tempo, source
104
105    s = source(source_uri, samplerate, hopsize)
106    if samplerate == 0:
107        samplerate = s.samplerate
108        options.samplerate = samplerate
109
110    if options.beat:
111        o = tempo(options.onset_method, bufsize, hopsize,
112                samplerate=samplerate)
113    else:
114        o = onset(options.onset_method, bufsize, hopsize,
115                samplerate=samplerate)
116        if options.minioi:
117            if options.minioi.endswith('ms'):
118                o.set_minioi_ms(int(options.minioi[:-2]))
119            elif options.minioi.endswith('s'):
120                o.set_minioi_s(int(options.minioi[:-1]))
121            else:
122                o.set_minioi(int(options.minioi))
123    o.set_threshold(options.threshold)
124
125    timestamps = []
126    total_frames = 0
127    while True:
128        samples, read = s()
129        if o(samples):
130            timestamps.append(o.get_last())
131            if options.verbose:
132                print("%.4f" % o.get_last_s())
133        total_frames += read
134        if read < hopsize:
135            break
136    del s
137    return timestamps, total_frames
138
139
140def _cut_slice(options, timestamps):
141    # cutting pass
142    nstamps = len(timestamps)
143    if nstamps > 0:
144        # generate output files
145        timestamps_end = None
146        if options.cut_every_nslices:
147            timestamps = timestamps[::options.cut_every_nslices]
148            nstamps = len(timestamps)
149        if options.cut_until_nslices and options.cut_until_nsamples:
150            msg = "using cut_until_nslices, but cut_until_nsamples is set"
151            warnings.warn(msg)
152        if options.cut_until_nsamples:
153            lag = options.cut_until_nsamples
154            timestamps_end = [t + lag for t in timestamps[1:]]
155            timestamps_end += [1e120]
156        if options.cut_until_nslices:
157            slice_lag = options.cut_until_nslices
158            timestamps_end = [t for t in timestamps[1 + slice_lag:]]
159            timestamps_end += [1e120] * (options.cut_until_nslices + 1)
160        slice_source_at_stamps(options.source_uri,
161                timestamps, timestamps_end = timestamps_end,
162                output_dir = options.output_directory,
163                samplerate = options.samplerate,
164                create_first = options.create_first)
165
166def main():
167    parser = aubio_cut_parser()
168    options = parser.parse_args()
169    if not options.source_uri and not options.source_uri2:
170        sys.stderr.write("Error: no file name given\n")
171        parser.print_help()
172        sys.exit(1)
173    elif options.source_uri2 is not None:
174        options.source_uri = options.source_uri2
175
176    # analysis
177    timestamps, total_frames = _cut_analyze(options)
178
179    # print some info
180    duration = float(total_frames) / float(options.samplerate)
181    base_info = '%(source_uri)s' % {'source_uri': options.source_uri}
182    base_info += ' (total %(duration).2fs at %(samplerate)dHz)\n' % \
183            {'duration': duration, 'samplerate': options.samplerate}
184
185    info = "found %d timestamps in " % len(timestamps)
186    info += base_info
187    sys.stderr.write(info)
188
189    if options.cut:
190        _cut_slice(options, timestamps)
191        info = "created %d slices from " % len(timestamps)
192        info += base_info
193        sys.stderr.write(info)
Note: See TracBrowser for help on using the repository browser.