Skip to content

Commit

Permalink
Add midi2note() and the corresponding unittest.
Browse files Browse the repository at this point in the history
  • Loading branch information
xaviliz committed May 22, 2024
1 parent e50ed5e commit 6cb342c
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/python/essentia/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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) )

Expand All @@ -98,6 +101,7 @@ def derivative(array):
'mel2hz', 'hz2mel',
'midi2hz', 'hz2midi',
'hz2cents',
'midi2note',
'postProcessTicks',
'normalize', 'derivative',
'equivalentKey', 'lin2log']
14 changes: 14 additions & 0 deletions src/python/globalfuncs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down Expand Up @@ -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" },
Expand Down
5 changes: 5 additions & 0 deletions test/src/unittests/base/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down

0 comments on commit 6cb342c

Please sign in to comment.