- Timestamp:
- Nov 17, 2018, 10:19:27 PM (6 years ago)
- Branches:
- feature/constantq
- Children:
- d1d4ad4
- Parents:
- 088760e (diff), a114fe0 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the(diff)
links above to see all the changes relative to each parent. - Location:
- python
- Files:
-
- 2 added
- 2 deleted
- 22 edited
Legend:
- Unmodified
- Added
- Removed
-
python/demos/demo_filter.py
r088760e rc03d191 4 4 import os.path 5 5 import aubio 6 6 7 7 8 def apply_filter(path, target): … … 28 29 total_frames += read 29 30 # end of file reached 30 if read < s.hop_size: break 31 if read < s.hop_size: 32 break 31 33 32 34 # print some info … … 34 36 input_str = "input: {:s} ({:.2f} s, {:d} Hz)" 35 37 output_str = "output: {:s}, A-weighting filtered ({:d} frames total)" 36 print 37 print 38 print(input_str.format(s.uri, duration, samplerate)) 39 print(output_str.format(o.uri, total_frames)) 38 40 39 41 if __name__ == '__main__': 40 42 usage = "{:s} <input_file> [output_file]".format(sys.argv[0]) 41 43 if not 1 < len(sys.argv) < 4: 42 print 44 print(usage) 43 45 sys.exit(1) 44 46 if len(sys.argv) < 3: -
python/demos/demo_filterbank.py
r088760e rc03d191 1 1 #! /usr/bin/env python 2 2 3 from aubio import filterbank, fvec 4 from pylab import loglog, show, xlim, ylim, xlabel, ylabel, title 5 from numpy import vstack, arange 3 """Create a filterbank from a list of frequencies. 6 4 5 This demo uses `aubio.filterbank.set_triangle_bands` to build a set of 6 triangular filters from a list of frequencies. 7 8 The filterbank coefficients are then modified before being displayed.""" 9 10 import aubio 11 import numpy as np 12 import matplotlib.pyplot as plt 13 14 # sampling rate and size of the fft 15 samplerate = 48000 7 16 win_s = 2048 8 samplerate = 480009 17 18 # define a list of custom frequency 10 19 freq_list = [60, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 24000] 20 # number of filters to create 11 21 n_filters = len(freq_list) - 2 12 22 13 f = filterbank(n_filters, win_s) 14 freqs = fvec(freq_list) 23 # create a new filterbank 24 f = aubio.filterbank(n_filters, win_s) 25 freqs = aubio.fvec(freq_list) 15 26 f.set_triangle_bands(freqs, samplerate) 16 27 28 # get the coefficients from the filterbank 17 29 coeffs = f.get_coeffs() 18 coeffs[4] *= 5. 19 30 # apply a gain to fifth band 31 coeffs[4] *= 6. 32 # load the modified coeffs into the filterbank 20 33 f.set_coeffs(coeffs) 21 34 22 times = vstack([arange(win_s // 2 + 1) * samplerate / win_s] * n_filters) 23 title('Bank of filters built using a simple list of boundaries\nThe middle band has been amplified by 2.') 24 loglog(times.T, f.get_coeffs().T, '.-') 25 xlim([50, samplerate/2]) 26 ylim([1.0e-6, 2.0e-2]) 27 xlabel('log frequency (Hz)') 28 ylabel('log amplitude') 29 30 show() 35 # display the band gains in a loglog plot 36 freqs = np.vstack([np.arange(win_s // 2 + 1) * samplerate / win_s] * n_filters) 37 plt.title('filterbank built from a list of frequencies\n' 38 'The 5th band has been amplified by a factor 6.') 39 plt.loglog(freqs.T, f.get_coeffs().T, '.-') 40 plt.xlim([50, samplerate/2]) 41 plt.ylim([1.0e-6, 2.0e-2]) 42 plt.xlabel('log frequency (Hz)') 43 plt.ylabel('log amplitude') 44 plt.show() -
python/demos/demo_source_simple.py
r088760e rc03d191 1 1 #! /usr/bin/env python 2 3 """A simple example using aubio.source.""" 4 2 5 import sys 3 6 import aubio 4 7 5 samplerate = 0 # use original source samplerate6 hop_size = 256 # number of frames to read in one block8 samplerate = 0 # use original source samplerate 9 hop_size = 256 # number of frames to read in one block 7 10 src = aubio.source(sys.argv[1], samplerate, hop_size) 8 11 total_frames = 0 9 12 10 13 while True: 11 samples, read = src() # read hop_size new samples from source 12 total_frames += read # increment total number of frames 13 if read < hop_size: break # end of file reached 14 samples, read = src() # read hop_size new samples from source 15 total_frames += read # increment total number of frames 16 if read < hop_size: # end of file reached 17 break 14 18 15 19 fmt_string = "read {:d} frames at {:d}Hz from {:s}" 16 print 20 print(fmt_string.format(total_frames, src.samplerate, src.uri)) -
python/ext/aubiomodule.c
r088760e rc03d191 373 373 {"shift", Py_aubio_shift, METH_VARARGS, Py_aubio_shift_doc}, 374 374 {"ishift", Py_aubio_ishift, METH_VARARGS, Py_aubio_ishift_doc}, 375 {"hztomel", Py_aubio_hztomel, METH_VARARGS|METH_KEYWORDS, Py_aubio_hztomel_doc}, 376 {"meltohz", Py_aubio_meltohz, METH_VARARGS|METH_KEYWORDS, Py_aubio_meltohz_doc}, 377 {"hztomel_htk", Py_aubio_hztomel_htk, METH_VARARGS, Py_aubio_hztomel_htk_doc}, 378 {"meltohz_htk", Py_aubio_meltohz_htk, METH_VARARGS, Py_aubio_meltohz_htk_doc}, 375 379 {NULL, NULL, 0, NULL} /* Sentinel */ 376 380 }; -
python/ext/py-filterbank.c
r088760e rc03d191 139 139 &(self->freqs), samplerate); 140 140 if (err > 0) { 141 PyErr_SetString (PyExc_ValueError, 142 "error when running set_triangle_bands"); 141 if (PyErr_Occurred() == NULL) { 142 PyErr_SetString (PyExc_ValueError, "error running set_triangle_bands"); 143 } else { 144 // change the RuntimeError into ValueError 145 PyObject *type, *value, *traceback; 146 PyErr_Fetch(&type, &value, &traceback); 147 PyErr_Restore(PyExc_ValueError, value, traceback); 148 } 143 149 return NULL; 144 150 } … … 151 157 uint_t err = 0; 152 158 153 uint_t samplerate;154 if (!PyArg_ParseTuple (args, "I", &samplerate)) {159 smpl_t samplerate; 160 if (!PyArg_ParseTuple (args, AUBIO_NPY_SMPL_CHR, &samplerate)) { 155 161 return NULL; 156 162 } … … 158 164 err = aubio_filterbank_set_mel_coeffs_slaney (self->o, samplerate); 159 165 if (err > 0) { 160 PyErr_SetString (PyExc_ValueError, 161 "error when running set_mel_coeffs_slaney"); 166 if (PyErr_Occurred() == NULL) { 167 PyErr_SetString (PyExc_ValueError, "error running set_mel_coeffs_slaney"); 168 } else { 169 // change the RuntimeError into ValueError 170 PyObject *type, *value, *traceback; 171 PyErr_Fetch(&type, &value, &traceback); 172 PyErr_Restore(PyExc_ValueError, value, traceback); 173 } 174 return NULL; 175 } 176 Py_RETURN_NONE; 177 } 178 179 static PyObject * 180 Py_filterbank_set_mel_coeffs (Py_filterbank * self, PyObject *args) 181 { 182 uint_t err = 0; 183 184 smpl_t samplerate; 185 smpl_t freq_min; 186 smpl_t freq_max; 187 if (!PyArg_ParseTuple (args, AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR 188 AUBIO_NPY_SMPL_CHR, &samplerate, &freq_min, &freq_max)) { 189 return NULL; 190 } 191 192 err = aubio_filterbank_set_mel_coeffs (self->o, samplerate, 193 freq_min, freq_max); 194 if (err > 0) { 195 if (PyErr_Occurred() == NULL) { 196 PyErr_SetString (PyExc_ValueError, "error running set_mel_coeffs"); 197 } else { 198 // change the RuntimeError into ValueError 199 PyObject *type, *value, *traceback; 200 PyErr_Fetch(&type, &value, &traceback); 201 PyErr_Restore(PyExc_ValueError, value, traceback); 202 } 203 return NULL; 204 } 205 Py_RETURN_NONE; 206 } 207 208 static PyObject * 209 Py_filterbank_set_mel_coeffs_htk (Py_filterbank * self, PyObject *args) 210 { 211 uint_t err = 0; 212 213 smpl_t samplerate; 214 smpl_t freq_min; 215 smpl_t freq_max; 216 if (!PyArg_ParseTuple (args, AUBIO_NPY_SMPL_CHR AUBIO_NPY_SMPL_CHR 217 AUBIO_NPY_SMPL_CHR, &samplerate, &freq_min, &freq_max)) { 218 return NULL; 219 } 220 221 err = aubio_filterbank_set_mel_coeffs_htk (self->o, samplerate, 222 freq_min, freq_max); 223 if (err > 0) { 224 if (PyErr_Occurred() == NULL) { 225 PyErr_SetString (PyExc_ValueError, "error running set_mel_coeffs_htk"); 226 } else { 227 // change the RuntimeError into ValueError 228 PyObject *type, *value, *traceback; 229 PyErr_Fetch(&type, &value, &traceback); 230 PyErr_Restore(PyExc_ValueError, value, traceback); 231 } 162 232 return NULL; 163 233 } … … 194 264 return (PyObject *)PyAubio_CFmatToArray( 195 265 aubio_filterbank_get_coeffs (self->o) ); 266 } 267 268 static PyObject * 269 Py_filterbank_set_power(Py_filterbank *self, PyObject *args) 270 { 271 uint_t power; 272 273 if (!PyArg_ParseTuple (args, "I", &power)) { 274 return NULL; 275 } 276 if(aubio_filterbank_set_power (self->o, power)) { 277 if (PyErr_Occurred() == NULL) { 278 PyErr_SetString (PyExc_ValueError, 279 "error running filterbank.set_power"); 280 } else { 281 // change the RuntimeError into ValueError 282 PyObject *type, *value, *traceback; 283 PyErr_Fetch(&type, &value, &traceback); 284 PyErr_Restore(PyExc_ValueError, value, traceback); 285 } 286 return NULL; 287 } 288 Py_RETURN_NONE; 289 } 290 291 static PyObject * 292 Py_filterbank_set_norm(Py_filterbank *self, PyObject *args) 293 { 294 uint_t playing; 295 296 if (!PyArg_ParseTuple (args, "I", &playing)) { 297 return NULL; 298 } 299 if(aubio_filterbank_set_norm (self->o, playing)) { 300 if (PyErr_Occurred() == NULL) { 301 PyErr_SetString (PyExc_ValueError, 302 "error running filterbank.set_power"); 303 } else { 304 // change the RuntimeError into ValueError 305 PyObject *type, *value, *traceback; 306 PyErr_Fetch(&type, &value, &traceback); 307 PyErr_Restore(PyExc_ValueError, value, traceback); 308 } 309 return NULL; 310 } 311 Py_RETURN_NONE; 196 312 } 197 313 … … 201 317 {"set_mel_coeffs_slaney", (PyCFunction) Py_filterbank_set_mel_coeffs_slaney, 202 318 METH_VARARGS, "set coefficients of filterbank as in Auditory Toolbox"}, 319 {"set_mel_coeffs", (PyCFunction) Py_filterbank_set_mel_coeffs, 320 METH_VARARGS, "set coefficients of filterbank to linearly spaced mel scale"}, 321 {"set_mel_coeffs_htk", (PyCFunction) Py_filterbank_set_mel_coeffs_htk, 322 METH_VARARGS, "set coefficients of filterbank to linearly spaced mel scale"}, 203 323 {"get_coeffs", (PyCFunction) Py_filterbank_get_coeffs, 204 324 METH_NOARGS, "get coefficients of filterbank"}, 205 325 {"set_coeffs", (PyCFunction) Py_filterbank_set_coeffs, 206 326 METH_VARARGS, "set coefficients of filterbank"}, 327 {"set_power", (PyCFunction) Py_filterbank_set_power, 328 METH_VARARGS, "set power applied to filterbank input spectrum"}, 329 {"set_norm", (PyCFunction) Py_filterbank_set_norm, 330 METH_VARARGS, "set norm applied to filterbank input spectrum"}, 207 331 {NULL} 208 332 }; -
python/ext/py-musicutils.c
r088760e rc03d191 182 182 return (PyObject *) PyAubio_CFvecToArray(&vec); 183 183 } 184 185 PyObject* 186 Py_aubio_hztomel(PyObject *self, PyObject *args, PyObject *kwds) 187 { 188 smpl_t v; 189 PyObject *htk = NULL; 190 static char *kwlist[] = {"f", "htk", NULL}; 191 if (!PyArg_ParseTupleAndKeywords(args, kwds, AUBIO_NPY_SMPL_CHR "|O", 192 kwlist, &v, &htk)) 193 { 194 return NULL; 195 } 196 if (htk != NULL && PyObject_IsTrue(htk) == 1) 197 return Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_hztomel_htk(v)); 198 else 199 return Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_hztomel(v)); 200 } 201 202 PyObject* 203 Py_aubio_meltohz(PyObject *self, PyObject *args, PyObject *kwds) 204 { 205 smpl_t v; 206 PyObject *htk = NULL; 207 static char *kwlist[] = {"m", "htk", NULL}; 208 if (!PyArg_ParseTupleAndKeywords(args, kwds, AUBIO_NPY_SMPL_CHR "|O", 209 kwlist, &v, &htk)) 210 { 211 return NULL; 212 } 213 if (htk != NULL && PyObject_IsTrue(htk) == 1) 214 return Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_meltohz_htk(v)); 215 else 216 return Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_meltohz(v)); 217 } 218 219 PyObject* 220 Py_aubio_hztomel_htk(PyObject *self, PyObject *args) 221 { 222 smpl_t v; 223 if (!PyArg_ParseTuple(args, AUBIO_NPY_SMPL_CHR, &v)) { 224 return NULL; 225 } 226 return Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_hztomel_htk(v)); 227 } 228 229 PyObject* 230 Py_aubio_meltohz_htk(PyObject *self, PyObject *args) 231 { 232 smpl_t v; 233 if (!PyArg_ParseTuple(args, AUBIO_NPY_SMPL_CHR, &v)) { 234 return NULL; 235 } 236 return Py_BuildValue(AUBIO_NPY_SMPL_CHR, aubio_meltohz_htk(v)); 237 } -
python/ext/py-musicutils.h
r088760e rc03d191 301 301 PyObject * Py_aubio_ishift(PyObject *self, PyObject *args); 302 302 303 static char Py_aubio_hztomel_doc[] = "" 304 "hztomel(f, htk=False)\n" 305 "\n" 306 "Convert a scalar from frequency to mel scale.\n" 307 "\n" 308 "Parameters\n" 309 "----------\n" 310 "m : float\n" 311 " input frequency, in Hz\n" 312 "htk : bool\n" 313 " if `True`, use Htk mel scale instead of Slaney.\n" 314 "\n" 315 "Returns\n" 316 "-------\n" 317 "float\n" 318 " output mel\n" 319 "\n" 320 "See Also\n" 321 "--------\n" 322 "meltohz\n" 323 ""; 324 PyObject * Py_aubio_hztomel(PyObject *self, PyObject *args); 325 326 static char Py_aubio_meltohz_doc[] = "" 327 "meltohz(m, htk=False)\n" 328 "\n" 329 "Convert a scalar from mel scale to frequency.\n" 330 "\n" 331 "Parameters\n" 332 "----------\n" 333 "m : float\n" 334 " input mel\n" 335 "htk : bool\n" 336 " if `True`, use Htk mel scale instead of Slaney.\n" 337 "\n" 338 "Returns\n" 339 "-------\n" 340 "float\n" 341 " output frequency, in Hz\n" 342 "\n" 343 "See Also\n" 344 "--------\n" 345 "hztomel\n" 346 ""; 347 PyObject * Py_aubio_meltohz(PyObject *self, PyObject *args); 348 349 static char Py_aubio_hztomel_htk_doc[] = "" 350 "hztomel_htk(m)\n" 351 "\n" 352 "Same as `hztomel(m, htk=True)`\n" 353 "\n" 354 "See Also\n" 355 "--------\n" 356 "hztomel\n" 357 ""; 358 PyObject * Py_aubio_hztomel_htk(PyObject *self, PyObject *args); 359 360 static char Py_aubio_meltohz_htk_doc[] = "" 361 "meltohz_htk(m)\n" 362 "\n" 363 "Same as `meltohz(m, htk=True)`\n" 364 "\n" 365 "See Also\n" 366 "--------\n" 367 "meltohz\n" 368 ""; 369 PyObject * Py_aubio_meltohz_htk(PyObject *self, PyObject *args); 370 303 371 #endif /* PY_AUBIO_MUSICUTILS_H */ -
python/ext/py-sink.c
r088760e rc03d191 15 15 "sink(path, samplerate=44100, channels=1)\n" 16 16 "\n" 17 " Open `path` to write a WAVfile.\n"17 "Write audio samples to file.\n" 18 18 "\n" 19 19 "Parameters\n" -
python/ext/py-source.c
r088760e rc03d191 19 19 "source(path, samplerate=0, hop_size=512, channels=0)\n" 20 20 "\n" 21 " Create a new source, opening the given pathname for reading.\n"21 "Read audio samples from a media file.\n" 22 22 "\n" 23 23 "`source` open the file specified in `path` and creates a callable\n" … … 248 248 "Returns\n" 249 249 "-------\n" 250 "samples : numpy.ndarray , shape `(hop_size,)`, dtype aubio.float_type\n"250 "samples : numpy.ndarray\n" 251 251 " `fvec` of size `hop_size` containing the new samples.\n" 252 252 "read : int\n" … … 284 284 "Returns\n" 285 285 "-------\n" 286 "samples : n p.ndarray([hop_size, channels], dtype=aubio.float_type)\n"286 "samples : numpy.ndarray\n" 287 287 " NumPy array of shape `(hop_size, channels)` containing the new\n" 288 288 " audio samples.\n" -
python/lib/aubio/__init__.py
r088760e rc03d191 29 29 from .midiconv import * 30 30 from .slicing import * 31 31 32 32 33 class fvec(numpy.ndarray): -
python/lib/aubio/cmd.py
r088760e rc03d191 12 12 import sys 13 13 import argparse 14 import warnings 14 15 import aubio 15 16 … … 169 170 170 171 def add_verbose_help(self): 171 self.add_argument("-v", "--verbose",172 self.add_argument("-v", "--verbose", 172 173 action="count", dest="verbose", default=1, 173 174 help="make lots of noise [default]") 174 self.add_argument("-q", "--quiet",175 self.add_argument("-q", "--quiet", 175 176 action="store_const", dest="verbose", const=0, 176 177 help="be quiet") … … 181 182 182 183 def add_buf_size(self, buf_size=512): 183 self.add_argument("-B", "--bufsize",184 self.add_argument("-B", "--bufsize", 184 185 action="store", dest="buf_size", default=buf_size, 185 186 metavar = "<size>", type=int, … … 187 188 188 189 def add_hop_size(self, hop_size=256): 189 self.add_argument("-H", "--hopsize",190 self.add_argument("-H", "--hopsize", 190 191 metavar = "<size>", type=int, 191 192 action="store", dest="hop_size", default=hop_size, … … 193 194 194 195 def add_method(self, method='default', helpstr='method'): 195 self.add_argument("-m", "--method",196 self.add_argument("-m", "--method", 196 197 metavar = "<method>", type=str, 197 198 action="store", dest="method", default=method, … … 199 200 200 201 def add_threshold(self, default=None): 201 self.add_argument("-t", "--threshold",202 self.add_argument("-t", "--threshold", 202 203 metavar = "<threshold>", type=float, 203 204 action="store", dest="threshold", default=default, … … 240 241 241 242 def add_slicer_options(self): 242 self.add_argument("-o", "--output", type = str,243 self.add_argument("-o", "--output", type = str, 243 244 metavar = "<outputdir>", 244 245 action="store", dest="output_directory", default=None, 245 help="specify path where slices of the original file should be created") 246 help="specify path where slices of the original file should" 247 " be created") 246 248 self.add_argument("--cut-until-nsamples", type = int, 247 249 metavar = "<samples>", 248 250 action = "store", dest = "cut_until_nsamples", default = None, 249 help="how many extra samples should be added at the end of each slice") 251 help="how many extra samples should be added at the end of" 252 " each slice") 250 253 self.add_argument("--cut-every-nslices", type = int, 251 254 metavar = "<samples>", … … 255 258 metavar = "<slices>", 256 259 action = "store", dest = "cut_until_nslices", default = None, 257 help="how many extra slices should be added at the end of each slice") 260 help="how many extra slices should be added at the end of" 261 " each slice") 258 262 self.add_argument("--create-first", 259 263 action = "store_true", dest = "create_first", default = False, … … 289 293 if args.verbose > 2 and hasattr(self, 'options'): 290 294 name = type(self).__name__.split('_')[1] 291 optstr = ' '.join(['running', name, 'with options', repr(self.options), '\n']) 295 optstr = ' '.join(['running', name, 'with options', 296 repr(self.options), '\n']) 292 297 sys.stderr.write(optstr) 293 298 def flush(self, frames_read, samplerate): … … 297 302 def parse_options(self, args, valid_opts): 298 303 # get any valid options found in a dictionnary of arguments 299 options = {k :v for k,v in vars(args).items() if k in valid_opts}304 options = {k: v for k, v in vars(args).items() if k in valid_opts} 300 305 self.options = options 301 306 … … 378 383 outstr = "unknown bpm" 379 384 else: 380 bpms = 60. / np.diff(self.beat_locations)385 bpms = 60. / np.diff(self.beat_locations) 381 386 median_bpm = np.mean(bpms) 382 387 if len(self.beat_locations) < 10: … … 399 404 return self.notes(block) 400 405 def repr_res(self, res, frames_read, samplerate): 401 if res[2] != 0: # note off406 if res[2] != 0: # note off 402 407 fmt_out = self.time2string(frames_read, samplerate) 403 408 sys.stdout.write(fmt_out + '\n') 404 if res[0] != 0: # note on409 if res[0] != 0: # note on 405 410 lastmidi = res[0] 406 411 fmt_out = "%f\t" % lastmidi 407 412 fmt_out += self.time2string(frames_read, samplerate) 408 sys.stdout.write(fmt_out) # + '\t')413 sys.stdout.write(fmt_out) # + '\t') 409 414 def flush(self, frames_read, samplerate): 410 415 eof = self.time2string(frames_read, samplerate) … … 473 478 if self.wassilence != 1: 474 479 self.wassilence = 1 475 return 2 # newly found silence476 return 1 # silence again480 return 2 # newly found silence 481 return 1 # silence again 477 482 else: 478 483 if self.wassilence != 0: 479 484 self.wassilence = 0 480 return -1 # newly found noise481 return 0 # noise again485 return -1 # newly found noise 486 return 0 # noise again 482 487 483 488 def repr_res(self, res, frames_read, samplerate): … … 499 504 def __call__(self, block): 500 505 ret = super(process_cut, self).__call__(block) 501 if ret: self.slices.append(self.onset.get_last()) 506 if ret: 507 self.slices.append(self.onset.get_last()) 502 508 return ret 503 509 504 510 def flush(self, frames_read, samplerate): 505 from aubio.cut import _cut_slice506 511 _cut_slice(self.options, self.slices) 507 duration = float (frames_read) / float(samplerate) 508 base_info = '%(source_file)s' % {'source_file': self.options.source_uri} 512 duration = float(frames_read) / float(samplerate) 513 base_info = '%(source_file)s' % \ 514 {'source_file': self.options.source_uri} 509 515 base_info += ' (total %(duration).2fs at %(samplerate)dHz)\n' % \ 510 {'duration': duration, 'samplerate': samplerate}516 {'duration': duration, 'samplerate': samplerate} 511 517 info = "created %d slices from " % len(self.slices) 512 518 info += base_info 513 519 sys.stderr.write(info) 520 521 def _cut_slice(options, timestamps): 522 # cutting pass 523 nstamps = len(timestamps) 524 if nstamps > 0: 525 # generate output files 526 timestamps_end = None 527 if options.cut_every_nslices: 528 timestamps = timestamps[::options.cut_every_nslices] 529 nstamps = len(timestamps) 530 if options.cut_until_nslices and options.cut_until_nsamples: 531 msg = "using cut_until_nslices, but cut_until_nsamples is set" 532 warnings.warn(msg) 533 if options.cut_until_nsamples: 534 lag = options.cut_until_nsamples 535 timestamps_end = [t + lag for t in timestamps[1:]] 536 timestamps_end += [1e120] 537 if options.cut_until_nslices: 538 slice_lag = options.cut_until_nslices 539 timestamps_end = [t for t in timestamps[1 + slice_lag:]] 540 timestamps_end += [1e120] * (options.cut_until_nslices + 1) 541 aubio.slice_source_at_stamps(options.source_uri, 542 timestamps, timestamps_end = timestamps_end, 543 output_dir = options.output_directory, 544 samplerate = options.samplerate, 545 create_first = options.create_first) 514 546 515 547 def main(): … … 526 558 action="store_true", dest="show_version") 527 559 args, extras = parser_root.parse_known_args() 528 if args.show_version == False:# no -V, forward to parser560 if not args.show_version: # no -V, forward to parser 529 561 args = parser.parse_args(extras, namespace=args) 530 elif len(extras) != 0: # -V with other arguments, print help562 elif len(extras) != 0: # -V with other arguments, print help 531 563 parser.print_help() 532 564 sys.exit(1) 533 else: # in py3, we can simply use parser directly565 else: # in py3, we can simply use parser directly 534 566 args = parser.parse_args() 535 567 if 'show_version' in args and args.show_version: … … 538 570 elif 'verbose' in args and args.verbose > 3: 539 571 sys.stderr.write('aubio version ' + aubio.version + '\n') 540 if 'command' not in args or args.command is None or args.command in ['help']: 572 if 'command' not in args or args.command is None \ 573 or args.command in ['help']: 541 574 # no command given, print help and return 1 542 575 parser.print_help() … … 572 605 frames_read += read 573 606 # exit loop at end of file 574 if read < a_source.hop_size: break 607 if read < a_source.hop_size: 608 break 575 609 # flush the processor if needed 576 610 processor.flush(frames_read, a_source.samplerate) … … 580 614 fmt_string += " from {:s} at {:d}Hz\n" 581 615 sys.stderr.write(fmt_string.format( 582 frames_read /float(a_source.samplerate),616 frames_read / float(a_source.samplerate), 583 617 frames_read, 584 618 frames_read // a_source.hop_size + 1, -
python/lib/aubio/cut.py
r088760e rc03d191 6 6 7 7 import sys 8 from aubio.cmd import AubioArgumentParser 8 from aubio.cmd import AubioArgumentParser, _cut_slice 9 9 10 10 def aubio_cut_parser(): 11 11 parser = AubioArgumentParser() 12 12 parser.add_input() 13 parser.add_argument("-O", "--onset-method",13 parser.add_argument("-O", "--onset-method", 14 14 action="store", dest="onset_method", default='default', 15 15 metavar = "<onset_method>", … … 17 17 complexdomain|hfc|phase|specdiff|energy|kl|mkl") 18 18 # cutting methods 19 parser.add_argument("-b", "--beat",19 parser.add_argument("-b", "--beat", 20 20 action="store_true", dest="beat", default=False, 21 21 help="slice at beat locations") 22 22 """ 23 parser.add_argument("-S", "--silencecut",23 parser.add_argument("-S", "--silencecut", 24 24 action="store_true", dest="silencecut", default=False, 25 25 help="use silence locations") 26 parser.add_argument("-s", "--silence",26 parser.add_argument("-s", "--silence", 27 27 metavar = "<value>", 28 28 action="store", dest="silence", default=-70, … … 31 31 # algorithm parameters 32 32 parser.add_buf_hop_size() 33 parser.add_argument("-t", "--threshold", "--onset-threshold",33 parser.add_argument("-t", "--threshold", "--onset-threshold", 34 34 metavar = "<threshold>", type=float, 35 35 action="store", dest="threshold", default=0.3, 36 36 help="onset peak picking threshold [default=0.3]") 37 parser.add_argument("-c", "--cut",37 parser.add_argument("-c", "--cut", 38 38 action="store_true", dest="cut", default=False, 39 39 help="cut input sound file at detected labels") … … 41 41 42 42 """ 43 parser.add_argument("-D", "--delay",43 parser.add_argument("-D", "--delay", 44 44 action = "store", dest = "delay", type = float, 45 45 metavar = "<seconds>", default=0, 46 46 help="number of seconds to take back [default=system]\ 47 47 default system delay is 3*hopsize/samplerate") 48 parser.add_argument("-C", "--dcthreshold",48 parser.add_argument("-C", "--dcthreshold", 49 49 metavar = "<value>", 50 50 action="store", dest="dcthreshold", default=1., 51 51 help="onset peak picking DC component [default=1.]") 52 parser.add_argument("-L", "--localmin",52 parser.add_argument("-L", "--localmin", 53 53 action="store_true", dest="localmin", default=False, 54 54 help="use local minima after peak detection") 55 parser.add_argument("-d", "--derivate",55 parser.add_argument("-d", "--derivate", 56 56 action="store_true", dest="derivate", default=False, 57 57 help="derivate onset detection function") 58 parser.add_argument("-z", "--zerocross",58 parser.add_argument("-z", "--zerocross", 59 59 metavar = "<value>", 60 60 action="store", dest="zerothres", default=0.008, 61 61 help="zero-crossing threshold for slicing [default=0.00008]") 62 62 # plotting functions 63 parser.add_argument("-p", "--plot",63 parser.add_argument("-p", "--plot", 64 64 action="store_true", dest="plot", default=False, 65 65 help="draw plot") 66 parser.add_argument("-x", "--xsize",66 parser.add_argument("-x", "--xsize", 67 67 metavar = "<size>", 68 68 action="store", dest="xsize", default=1., 69 69 type=float, help="define xsize for plot") 70 parser.add_argument("-y", "--ysize",70 parser.add_argument("-y", "--ysize", 71 71 metavar = "<size>", 72 72 action="store", dest="ysize", default=1., 73 73 type=float, help="define ysize for plot") 74 parser.add_argument("-f", "--function",74 parser.add_argument("-f", "--function", 75 75 action="store_true", dest="func", default=False, 76 76 help="print detection function") 77 parser.add_argument("-n", "--no-onsets",77 parser.add_argument("-n", "--no-onsets", 78 78 action="store_true", dest="nplot", default=False, 79 79 help="do not plot detected onsets") 80 parser.add_argument("-O", "--outplot",80 parser.add_argument("-O", "--outplot", 81 81 metavar = "<output_image>", 82 82 action="store", dest="outplot", default=None, 83 83 help="save plot to output.{ps,png}") 84 parser.add_argument("-F", "--spectrogram",84 parser.add_argument("-F", "--spectrogram", 85 85 action="store_true", dest="spectro", default=False, 86 86 help="add spectrogram to the plot") … … 106 106 107 107 if options.beat: 108 o = tempo(options.onset_method, bufsize, hopsize, samplerate=samplerate) 108 o = tempo(options.onset_method, bufsize, hopsize, 109 samplerate=samplerate) 109 110 else: 110 o = onset(options.onset_method, bufsize, hopsize, samplerate=samplerate) 111 o = onset(options.onset_method, bufsize, hopsize, 112 samplerate=samplerate) 111 113 if options.minioi: 112 114 if options.minioi.endswith('ms'): … … 123 125 samples, read = s() 124 126 if o(samples): 125 timestamps.append (o.get_last()) 126 if options.verbose: print ("%.4f" % o.get_last_s()) 127 timestamps.append(o.get_last()) 128 if options.verbose: 129 print("%.4f" % o.get_last_s()) 127 130 total_frames += read 128 if read < hopsize: break 131 if read < hopsize: 132 break 129 133 del s 130 134 return timestamps, total_frames 131 132 def _cut_slice(options, timestamps):133 # cutting pass134 nstamps = len(timestamps)135 if nstamps > 0:136 # generate output files137 from aubio.slicing import slice_source_at_stamps138 timestamps_end = None139 if options.cut_every_nslices:140 timestamps = timestamps[::options.cut_every_nslices]141 nstamps = len(timestamps)142 if options.cut_until_nslices and options.cut_until_nsamples:143 print ("warning: using cut_until_nslices, but cut_until_nsamples is set")144 if options.cut_until_nsamples:145 timestamps_end = [t + options.cut_until_nsamples for t in timestamps[1:]]146 timestamps_end += [ 1e120 ]147 if options.cut_until_nslices:148 timestamps_end = [t for t in timestamps[1 + options.cut_until_nslices:]]149 timestamps_end += [ 1e120 ] * (options.cut_until_nslices + 1)150 slice_source_at_stamps(options.source_uri,151 timestamps, timestamps_end = timestamps_end,152 output_dir = options.output_directory,153 samplerate = options.samplerate,154 create_first = options.create_first)155 135 156 136 def main(): … … 168 148 169 149 # print some info 170 duration = float 150 duration = float(total_frames) / float(options.samplerate) 171 151 base_info = '%(source_uri)s' % {'source_uri': options.source_uri} 172 152 base_info += ' (total %(duration).2fs at %(samplerate)dHz)\n' % \ -
python/lib/aubio/midiconv.py
r088760e rc03d191 2 2 """ utilities to convert midi note number to and from note names """ 3 3 4 __all__ = ['note2midi', 'midi2note', 'freq2note', 'note2freq']5 6 4 import sys 7 5 from ._aubio import freqtomidi, miditofreq 6 7 __all__ = ['note2midi', 'midi2note', 'freq2note', 'note2freq'] 8 8 9 9 py3 = sys.version_info[0] == 3 … … 14 14 str_instances = (str, unicode) 15 15 int_instances = (int, long) 16 16 17 17 18 def note2midi(note): … … 56 57 midi2note, freqtomidi, miditofreq 57 58 """ 58 _valid_notenames = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11} 59 _valid_notenames = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 60 'A': 9, 'B': 11} 59 61 _valid_modifiers = { 60 u'𝄫': -2, # double flat61 u'♭': -1, 'b': -1, '\u266d': -1, # simple flat62 u'♮': 0, '\u266e': 0, None: 0, # natural63 '#': +1, u'♯': +1, '\u266f': +1, # sharp64 u'𝄪': +2, # double sharp62 u'𝄫': -2, # double flat 63 u'♭': -1, 'b': -1, '\u266d': -1, # simple flat 64 u'♮': 0, '\u266e': 0, None: 0, # natural 65 '#': +1, u'♯': +1, '\u266f': +1, # sharp 66 u'𝄪': +2, # double sharp 65 67 } 66 68 _valid_octaves = range(-1, 10) … … 71 73 msg = "string of 2 to 4 characters expected, got {:d} ({:s})" 72 74 raise ValueError(msg.format(len(note), note)) 73 notename, modifier, octave = [None] *375 notename, modifier, octave = [None] * 3 74 76 75 77 if len(note) == 4: … … 94 96 raise ValueError("%s is not a valid octave" % octave) 95 97 96 midi = 12 + octave* 12 + _valid_notenames[notename] \97 + _valid_modifiers[modifier]98 midi = (octave + 1) * 12 + _valid_notenames[notename] \ 99 + _valid_modifiers[modifier] 98 100 if midi > 127: 99 101 raise ValueError("%s is outside of the range C-2 to G8" % note) 100 102 return midi 103 101 104 102 105 def midi2note(midi): … … 137 140 raise ValueError(msg.format(midi)) 138 141 _valid_notenames = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 139 'A', 'A#', 'B']142 'A', 'A#', 'B'] 140 143 return _valid_notenames[midi % 12] + str(int(midi / 12) - 1) 144 141 145 142 146 def freq2note(freq): … … 163 167 return midi2note(nearest_note) 164 168 169 165 170 def note2freq(note): 166 171 """Convert note name to corresponding frequency, in Hz. -
python/lib/aubio/slicing.py
r088760e rc03d191 5 5 6 6 _max_timestamp = 1e120 7 7 8 8 9 def slice_source_at_stamps(source_file, timestamps, timestamps_end=None, … … 73 74 """ 74 75 75 if timestamps is None or len(timestamps) == 0:76 if not timestamps: 76 77 raise ValueError("no timestamps given") 77 78 … … 90 91 91 92 regions = list(zip(timestamps, timestamps_end)) 92 #print regions93 93 94 94 source_base_name, _ = os.path.splitext(os.path.basename(source_file)) … … 98 98 source_base_name = os.path.join(output_dir, source_base_name) 99 99 100 def new_sink_name(source_base_name, timestamp, samplerate):101 """ create a sink based on a timestamp in samples, converted in seconds """100 def _new_sink_name(source_base_name, timestamp, samplerate): 101 # create name based on a timestamp in samples, converted in seconds 102 102 timestamp_seconds = timestamp / float(samplerate) 103 103 return source_base_name + "_%011.6f" % timestamp_seconds + '.wav' … … 114 114 vec, read = _source.do_multi() 115 115 # if the total number of frames read will exceed the next region start 116 while len(regions) and total_frames + read >= regions[0][0]: 117 #print "getting", regions[0], "at", total_frames 116 while regions and total_frames + read >= regions[0][0]: 118 117 # get next region 119 118 start_stamp, end_stamp = regions.pop(0) 120 119 # create a name for the sink 121 new_sink_path = new_sink_name(source_base_name, start_stamp, samplerate) 120 new_sink_path = _new_sink_name(source_base_name, start_stamp, 121 samplerate) 122 122 # create its sink 123 123 _sink = sink(new_sink_path, samplerate, _source.channels) 124 124 # create a dictionary containing all this 125 new_slice = {'start_stamp': start_stamp, 'end_stamp': end_stamp, 'sink': _sink} 125 new_slice = {'start_stamp': start_stamp, 'end_stamp': end_stamp, 126 'sink': _sink} 126 127 # append the dictionary to the current list of slices 127 128 slices.append(new_slice) … … 135 136 # number of samples yet to written be until end of region 136 137 remaining = end_stamp - total_frames + 1 137 #print current_slice, remaining, start138 138 # not enough frames remaining, time to split 139 139 if remaining < read: … … 141 141 # write remaining samples from current region 142 142 _sink.do_multi(vec[:, start:remaining], remaining - start) 143 #print("closing region", "remaining", remaining)144 143 # close this file 145 144 _sink.close() … … 150 149 # remove old slices 151 150 slices = list(filter(lambda s: s['end_stamp'] > total_frames, 152 slices))151 slices)) 153 152 if read < hopsize: 154 153 break -
python/lib/gen_code.py
r088760e rc03d191 465 465 """.format(**self.__dict__) 466 466 for set_param in self.prototypes['set']: 467 params = get_params_types_names(set_param)[1] 468 paramtype = params['type'] 467 params = get_params_types_names(set_param)[1:] 468 param = self.shortname.split('_set_')[-1] 469 paramdecls = "".join([""" 470 {0} {1};""".format(p['type'], p['name']) for p in params]) 469 471 method_name = get_name(set_param) 470 472 param = method_name.split('aubio_'+self.shortname+'_set_')[-1] 471 pyparamtype = pyargparse_chars[paramtype] 473 refs = ", ".join(["&%s" % p['name'] for p in params]) 474 paramlist = ", ".join(["%s" % p['name'] for p in params]) 475 if len(params): 476 paramlist = "," + paramlist 477 pyparamtypes = ''.join([pyargparse_chars[p['type']] for p in params]) 472 478 out += """ 473 479 static PyObject * … … 475 481 {{ 476 482 uint_t err = 0; 477 {paramtype} {param}; 478 479 if (!PyArg_ParseTuple (args, "{pyparamtype}", &{param})) {{ 483 {paramdecls} 484 """.format(param = param, paramdecls = paramdecls, **self.__dict__) 485 486 if len(refs) and len(pyparamtypes): 487 out += """ 488 489 if (!PyArg_ParseTuple (args, "{pyparamtypes}", {refs})) {{ 480 490 return NULL; 481 491 }} 482 err = aubio_{shortname}_set_{param} (self->o, {param}); 492 """.format(pyparamtypes = pyparamtypes, refs = refs) 493 494 out += """ 495 err = aubio_{shortname}_set_{param} (self->o {paramlist}); 483 496 484 497 if (err > 0) {{ … … 495 508 Py_RETURN_NONE; 496 509 }} 497 """.format(param = param, paramtype = paramtype, pyparamtype = pyparamtype, **self.__dict__) 510 """.format(param = param, refs = refs, paramdecls = paramdecls, 511 pyparamtypes = pyparamtypes, paramlist = paramlist, **self.__dict__) 498 512 return out 499 513 -
python/lib/gen_external.py
r088760e rc03d191 4 4 import subprocess 5 5 import glob 6 from distutils.sysconfig import customize_compiler 7 from gen_code import MappedObject 6 8 7 9 header = os.path.join('src', 'aubio.h') … … 50 52 def get_preprocessor(): 51 53 # findout which compiler to use 52 from distutils.sysconfig import customize_compiler53 54 compiler_name = distutils.ccompiler.get_default_compiler() 54 55 compiler = distutils.ccompiler.new_compiler(compiler=compiler_name) … … 263 264 264 265 sources_list = [] 265 try:266 from .gen_code import MappedObject267 except (SystemError, ValueError):268 from gen_code import MappedObject269 266 for o in lib: 270 267 out = source_header -
python/lib/moresetuptools.py
r088760e rc03d191 3 3 import sys, os, glob, subprocess 4 4 import distutils, distutils.command.clean, distutils.dir_util 5 from .gen_external import generate_external, header, output_path5 from gen_external import generate_external, header, output_path 6 6 7 7 from this_version import get_aubio_version -
python/tests/test_fft.py
r088760e rc03d191 143 143 assert_almost_equal ( r[1:], 0) 144 144 145 class aubio_fft_odd_sizes(TestCase): 146 147 def test_reconstruct_with_odd_size(self): 148 win_s = 29 149 self.recontruct(win_s, 'odd sizes not supported') 150 151 def test_reconstruct_with_radix15(self): 152 win_s = 2 ** 4 * 15 153 self.recontruct(win_s, 'radix 15 supported') 154 155 def test_reconstruct_with_radix5(self): 156 win_s = 2 ** 4 * 5 157 self.recontruct(win_s, 'radix 5 supported') 158 159 def test_reconstruct_with_radix3(self): 160 win_s = 2 ** 4 * 3 161 self.recontruct(win_s, 'radix 3 supported') 162 163 def recontruct(self, win_s, skipMessage): 164 try: 165 f = fft(win_s) 166 except RuntimeError: 167 self.skipTest(skipMessage) 168 input_signal = fvec(win_s) 169 input_signal[win_s//2] = 1 170 c = f(input_signal) 171 output_signal = f.rdo(c) 172 assert_almost_equal(input_signal, output_signal) 173 174 class aubio_fft_wrong_params(TestCase): 175 145 176 def test_large_input_timegrain(self): 146 177 win_s = 1024 … … 170 201 with self.assertRaises(ValueError): 171 202 f.rdo(s) 172 173 class aubio_fft_wrong_params(TestCase):174 203 175 204 def test_wrong_buf_size(self): … … 177 206 with self.assertRaises(ValueError): 178 207 fft(win_s) 179 180 def test_buf_size_not_power_of_two(self):181 # when compiled with fftw3, aubio supports non power of two fft sizes182 win_s = 320183 try:184 with self.assertRaises(RuntimeError):185 fft(win_s)186 except AssertionError:187 self.skipTest('creating aubio.fft with size %d did not fail' % win_s)188 208 189 209 def test_buf_size_too_small(self): -
python/tests/test_filter.py
r088760e rc03d191 78 78 f.set_biquad(0., 0., 0, 0., 0.) 79 79 80 def test_all_available_presets(self): 81 f = digital_filter(7) 82 for sr in [8000, 11025, 16000, 22050, 24000, 32000, 83 44100, 48000, 88200, 96000, 192000]: 84 f.set_a_weighting(sr) 85 f = digital_filter(5) 86 for sr in [8000, 11025, 16000, 22050, 24000, 32000, 87 44100, 48000, 88200, 96000, 192000]: 88 f.set_c_weighting(sr) 89 80 90 class aubio_filter_wrong_params(TestCase): 81 91 -
python/tests/test_filterbank_mel.py
r088760e rc03d191 4 4 from numpy.testing import TestCase, assert_equal, assert_almost_equal 5 5 6 from aubio import cvec, filterbank, float_type6 from aubio import fvec, cvec, filterbank, float_type 7 7 8 8 import warnings … … 48 48 0.02133301, 0.02133301, 0.02133311, 0.02133334, 0.02133345]) 49 49 50 def test_triangle_freqs_with_zeros(self): 51 """make sure set_triangle_bands works when list starts with 0""" 52 freq_list = [0, 40, 80] 53 freqs = np.array(freq_list, dtype = float_type) 54 f = filterbank(len(freqs)-2, 1024) 55 f.set_triangle_bands(freqs, 48000) 56 assert_equal ( f(cvec(1024)), 0) 57 self.assertIsInstance(f.get_coeffs(), np.ndarray) 58 59 def test_triangle_freqs_with_wrong_negative(self): 60 """make sure set_triangle_bands fails when list contains a negative""" 61 freq_list = [-10, 0, 80] 62 f = filterbank(len(freq_list)-2, 1024) 63 with self.assertRaises(ValueError): 64 f.set_triangle_bands(fvec(freq_list), 48000) 65 66 def test_triangle_freqs_with_wrong_ordering(self): 67 """make sure set_triangle_bands fails when list not ordered""" 68 freq_list = [0, 80, 40] 69 f = filterbank(len(freq_list)-2, 1024) 70 with self.assertRaises(ValueError): 71 f.set_triangle_bands(fvec(freq_list), 48000) 72 73 def test_triangle_freqs_with_large_freq(self): 74 """make sure set_triangle_bands warns when freq > nyquist""" 75 samplerate = 22050 76 freq_list = [0, samplerate//4, samplerate // 2 + 1] 77 f = filterbank(len(freq_list)-2, 1024) 78 # TODO add assert_warns 79 f.set_triangle_bands(fvec(freq_list), samplerate) 80 81 def test_triangle_freqs_with_not_enough_filters(self): 82 """make sure set_triangle_bands warns when not enough filters""" 83 samplerate = 22050 84 freq_list = [0, 100, 1000, 4000, 8000, 10000] 85 f = filterbank(len(freq_list)-3, 1024) 86 # TODO add assert_warns 87 f.set_triangle_bands(fvec(freq_list), samplerate) 88 89 def test_triangle_freqs_with_too_many_filters(self): 90 """make sure set_triangle_bands warns when too many filters""" 91 samplerate = 22050 92 freq_list = [0, 100, 1000, 4000, 8000, 10000] 93 f = filterbank(len(freq_list)-1, 1024) 94 # TODO add assert_warns 95 f.set_triangle_bands(fvec(freq_list), samplerate) 96 97 def test_triangle_freqs_with_double_value(self): 98 """make sure set_triangle_bands works with 2 duplicate freqs""" 99 samplerate = 22050 100 freq_list = [0, 100, 1000, 4000, 4000, 4000, 10000] 101 f = filterbank(len(freq_list)-2, 1024) 102 # TODO add assert_warns 103 f.set_triangle_bands(fvec(freq_list), samplerate) 104 105 def test_triangle_freqs_with_triple(self): 106 """make sure set_triangle_bands works with 3 duplicate freqs""" 107 samplerate = 22050 108 freq_list = [0, 100, 1000, 4000, 4000, 4000, 10000] 109 f = filterbank(len(freq_list)-2, 1024) 110 # TODO add assert_warns 111 f.set_triangle_bands(fvec(freq_list), samplerate) 112 113 def test_triangle_freqs_without_norm(self): 114 """make sure set_triangle_bands works without """ 115 samplerate = 22050 116 freq_list = fvec([0, 100, 1000, 10000]) 117 f = filterbank(len(freq_list) - 2, 1024) 118 f.set_norm(0) 119 f.set_triangle_bands(freq_list, samplerate) 120 expected = f.get_coeffs() 121 f.set_norm(1) 122 f.set_triangle_bands(fvec(freq_list), samplerate) 123 assert_almost_equal(f.get_coeffs().T, 124 expected.T * 2. / (freq_list[2:] - freq_list[:-2])) 125 126 def test_triangle_freqs_wrong_norm(self): 127 f = filterbank(10, 1024) 128 with self.assertRaises(ValueError): 129 f.set_norm(-1) 130 131 def test_triangle_freqs_with_power(self): 132 f = filterbank(9, 1024) 133 freqs = fvec([40, 80, 200, 400, 800, 1600, 3200, 6400, 12800, 15000, 134 24000]) 135 f.set_power(2) 136 f.set_triangle_bands(freqs, 48000) 137 spec = cvec(1024) 138 spec.norm[:] = .1 139 expected = fvec([0.02070313, 0.02138672, 0.02127604, 0.02135417, 140 0.02133301, 0.02133301, 0.02133311, 0.02133334, 0.02133345]) 141 expected /= 100. 142 assert_almost_equal(f(spec), expected) 143 144 def test_mel_coeffs(self): 145 f = filterbank(40, 1024) 146 f.set_mel_coeffs(44100, 0, 44100 / 2) 147 148 def test_zero_fmax(self): 149 f = filterbank(40, 1024) 150 f.set_mel_coeffs(44100, 0, 0) 151 152 def test_wrong_mel_coeffs(self): 153 f = filterbank(40, 1024) 154 with self.assertRaises(ValueError): 155 f.set_mel_coeffs_slaney(0) 156 with self.assertRaises(ValueError): 157 f.set_mel_coeffs(44100, 0, -44100 / 2) 158 with self.assertRaises(ValueError): 159 f.set_mel_coeffs(44100, -0.1, 44100 / 2) 160 with self.assertRaises(ValueError): 161 f.set_mel_coeffs(-44100, 0.1, 44100 / 2) 162 with self.assertRaises(ValueError): 163 f.set_mel_coeffs_htk(-1, 0, 0) 164 165 def test_mel_coeffs_htk(self): 166 f = filterbank(40, 1024) 167 f.set_mel_coeffs_htk(44100, 0, 44100 / 2) 168 169 50 170 if __name__ == '__main__': 51 171 import nose2 -
python/tests/test_mfcc.py
r088760e rc03d191 111 111 #print coeffs 112 112 113 114 class aubio_mfcc_fb_params(TestCase): 115 116 def test_set_scale(self): 117 buf_size, n_filters, n_coeffs, samplerate = 512, 20, 10, 16000 118 m = mfcc(buf_size, n_filters, n_coeffs, samplerate) 119 m.set_scale(10.) 120 m(cvec(buf_size)) 121 122 def test_set_power(self): 123 buf_size, n_filters, n_coeffs, samplerate = 512, 20, 10, 16000 124 m = mfcc(buf_size, n_filters, n_coeffs, samplerate) 125 m.set_power(2.) 126 m(cvec(buf_size)) 127 128 def test_set_mel_coeffs(self): 129 buf_size, n_filters, n_coeffs, samplerate = 512, 20, 10, 16000 130 m = mfcc(buf_size, n_filters, n_coeffs, samplerate) 131 m.set_mel_coeffs(0., samplerate/2.) 132 m(cvec(buf_size)) 133 134 def test_set_mel_coeffs_htk(self): 135 buf_size, n_filters, n_coeffs, samplerate = 512, 20, 10, 16000 136 m = mfcc(buf_size, n_filters, n_coeffs, samplerate) 137 m.set_mel_coeffs_htk(0., samplerate/2.) 138 m(cvec(buf_size)) 139 140 def test_set_mel_coeffs_slaney(self): 141 buf_size, n_filters, n_coeffs, samplerate = 512, 40, 10, 16000 142 m = mfcc(buf_size, n_filters, n_coeffs, samplerate) 143 m.set_mel_coeffs_slaney(samplerate) 144 m(cvec(buf_size)) 145 assert m.get_power() == 1 146 assert m.get_scale() == 1 147 113 148 if __name__ == '__main__': 114 149 main() -
python/tests/test_onset.py
r088760e rc03d191 3 3 from unittest import main 4 4 from numpy.testing import TestCase, assert_equal, assert_almost_equal 5 from aubio import onset 5 from aubio import onset, fvec 6 6 7 7 class aubio_onset_default(TestCase): … … 84 84 samplerate = 8000 85 85 86 class aubio_onset_coverate(TestCase): 87 # extra tests to execute the C routines and improve coverage 88 89 def test_all_methods(self): 90 for method in ['default', 'energy', 'hfc', 'complexdomain', 'complex', 91 'phase', 'wphase', 'mkl', 'kl', 'specflux', 'specdiff', 92 'old_default']: 93 o = onset(method=method, buf_size=512, hop_size=256) 94 o(fvec(256)) 95 96 def test_get_methods(self): 97 o = onset(method='default', buf_size=512, hop_size=256) 98 99 assert o.get_silence() == -70 100 o.set_silence(-20) 101 assert_almost_equal(o.get_silence(), -20) 102 103 assert o.get_compression() == 1 104 o.set_compression(.99) 105 assert_almost_equal(o.get_compression(), .99) 106 107 assert o.get_awhitening() == 0 108 o.set_awhitening(1) 109 assert o.get_awhitening() == 1 110 111 o.get_last() 112 o.get_last_ms() 113 o.get_last_s() 114 o.get_descriptor() 115 o.get_thresholded_descriptor() 116 117 86 118 if __name__ == '__main__': 87 119 main()
Note: See TracChangeset
for help on using the changeset viewer.