MidiMessage::keyNameToNumber


#1

Hi Jules,

here’s a convenient function i think might have its place in MidiMessage. It converts midi note names to midi note numbers. It’s the opposite to MidiMessage::getMidiNoteName and I’ve found it useful when parsing soundfont files for example. Anyway it’s static so if it doesn’t make its way into the library it’s here for anyone who needs it!

[code]int MidiMessage::keyNameToNumber(const String& keyName) {

static const char* const noteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B", "", "Db", "", "Eb", "", "", "Gb", "", "Ab", "", "Bb" };

int keyNumber, octave = 0, numPos = keyName.indexOfAnyOf("01234567890-");

if (numPos == 0)
	keyNumber = keyName.getIntValue();	//apparently already a number!

else 
{
	if (numPos > 0) 
	{
		octave = keyName.substring(numPos).getIntValue() + 1;
	}
	else 
	{
		octave = 5;		//default to octave of middle C if none found
		numPos = keyName.length();
	}

	String name(keyName.substring(0, numPos).trim().toUpperCase());

	keyNumber = StringArray(noteNames, 12).indexOf(name) % 12;

	if (keyNumber < 0) {
		DBG("Phoney keyname: " << keyName);
	}
}

return keyNumber + octave * 12;

}
[/code]


Iterate through a JUCE String?
#2

Thanks! This is exactly what I need at the moment. I tweaked it so that you can pass in the octave number for middle C:

[code]int MidiMessage::keyNameToNumber(const String& keyName, const int octaveForMiddleC) {

static const char* const noteNames[] = { “C”, “C#”, “D”, “D#”, “E”, “F”, “F#”, “G”, “G#”, “A”, “A#”, “B”, “”, “Db”, “”, “Eb”, “”, “”, “Gb”, “”, “Ab”, “”, “Bb” };

int keyNumber, octave = 0, numPos = keyName.indexOfAnyOf(“01234567890-”);

if (numPos == 0)
keyNumber = keyName.getIntValue(); //apparently already a number!

else
{
if (numPos > 0)
{
octave = keyName.substring(numPos).getIntValue() - octaveForMiddleC + 5;
}
else
{
octave = octaveForMiddleC; //default to octave of middle C if none found
numPos = keyName.length();
}

  String name(keyName.substring(0, numPos).trim().toUpperCase());

  keyNumber = StringArray(noteNames, 12).indexOf(name) % 12;

  if (keyNumber < 0) {
     DBG("Phoney keyname: " << keyName);
  }

}

return keyNumber + octave * 12;
}[/code]