diff --git a/src/python/essentia/utils.py b/src/python/essentia/utils.py index fec9f5fe1..94d010fdc 100644 --- a/src/python/essentia/utils.py +++ b/src/python/essentia/utils.py @@ -73,6 +73,9 @@ def hz2cents(arg1, arg2): return _essentia.hz2cents(_c.convertData(arg1, _c.Edt.REAL), _c.convertData(arg2, _c.Edt.REAL) ) +def midi2note(arg): + return _essentia.midi2note( _c.convertData(arg, _c.Edt.INTEGER) ) + def equivalentKey(arg): return _essentia.equivalentKey( _c.convertData(arg, _c.Edt.STRING) ) @@ -98,6 +101,7 @@ def derivative(array): 'mel2hz', 'hz2mel', 'midi2hz', 'hz2midi', 'hz2cents', + 'midi2note', 'postProcessTicks', 'normalize', 'derivative', 'equivalentKey', 'lin2log'] diff --git a/src/python/globalfuncs.cpp b/src/python/globalfuncs.cpp index 047964149..c97d9e7e8 100644 --- a/src/python/globalfuncs.cpp +++ b/src/python/globalfuncs.cpp @@ -426,6 +426,19 @@ hzToCents(PyObject* notUsed, PyObject* args) { return PyFloat_FromDouble( int(cents) ); } +static PyObject* +midiToNote(PyObject* notUsed, PyObject* arg) { + + if (!PyLong_Check(arg)) { + PyErr_SetString(PyExc_TypeError, (char*)"argument must be an integer"); + return NULL; + } + + std::string note = midi2note( long( PyLong_AsLong(arg) ) ); + const char *c_note = note.c_str(); + return PyString_FromString( c_note ); +} + static PyObject* getEquivalentKey(PyObject* notUsed, PyObject* arg) { if (!PyString_Check(arg)) { @@ -1040,6 +1053,7 @@ static PyMethodDef Essentia__Methods[] = { { "midi2hz", midiToHz, METH_O, "Converts a midi note number to frequency in Hz" }, { "hz2midi", hzToMidi, METH_O, "Converts a frequency in Hz to a midi note number" }, { "hz2cents", hzToCents, METH_VARARGS, "Converts a frequency in Hz to cents" }, + { "midi2note", midiToNote, METH_O, "Converts a midi note number in the root note" }, { "lin2db", linToDb, METH_O, "Converts a linear measure of power to a measure in dB" }, { "db2lin", dbToLin, METH_O, "Converts a dB measure of power to a linear measure" }, { "db2pow", dbToPow, METH_O, "Converts a dB measure of power to a linear measure" }, diff --git a/test/src/unittests/base/test_utils.py b/test/src/unittests/base/test_utils.py index 4810b447b..d19d167d4 100644 --- a/test/src/unittests/base/test_utils.py +++ b/test/src/unittests/base/test_utils.py @@ -123,6 +123,11 @@ def testHzToCents(self): expected_cents = 100 self.assertAlmostEqual(expected_cents, hz2cents(midi2hz(midi), tuning)) + def testMidiToNote(self): + midi = 69 + expected_note = "A4" + self.assertEqual(expected_note, midi2note(midi)) + suite = allTests(TestUtils)