我已经写了以下方法来将音符(八度附加在末尾)转换为相应的MIDI音高:

// Converts a note string (MUST HAVE OCTAVE) to an integer pitch.
public static int convertToPitch(String note) {
    String sym = "";
    int oct = 0;

    String[] notes = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };

    char[] splitNote = note.toCharArray();

    // If the length is two, then grab the symbol and number.
    // Otherwise, it must be a two-char note.
    if (splitNote.length == 2) {
        sym += splitNote[0];
        oct = splitNote[1];
    } else if (splitNote.length == 3) {
        sym += Character.toString(splitNote[0]);
        sym += Character.toString(splitNote[1]);
        oct = splitNote[2];
    }

    // Find the corresponding note in the array.
    for (int i = 0; i < notes.length; i++) {
        if (notes[i].equals(sym)) {
            return Character.getNumericValue(oct) * 12 + i;
        }
    }

    // If nothing was found, we return -1.
    return -1;
}

而且效果非常好但是,我也希望能够使用convertToPitch()和替换注释值(Db变成C#,等等)来表示每个具有替换名称的注释有没有办法在不破坏我的方法的情况下做到这一点?

最佳答案

你可以这样做

public static int convertToPitch(String note) {
  String sym = "";
  int oct = 0;
  String[][] notes = { {"C"}, {"Db", "C#"}, {"D"}, {"Eb", "D#"}, {"E"},
    {"F"}, {"Gb", "F#"}, {"G"}, {"Ab", "G#"}, {"A"}, {"Bb", "A#"}, {"B"} };

  char[] splitNote = note.toCharArray();

  // If the length is two, then grab the symbol and number.
  // Otherwise, it must be a two-char note.
  if (splitNote.length == 2) {
    sym += splitNote[0];
    oct = splitNote[1];
  } else if (splitNote.length == 3) {
    sym += Character.toString(splitNote[0]);
    sym += Character.toString(splitNote[1]);
    oct = splitNote[2];
  }

  // Find the corresponding note in the array.
  for (int i = 0; i < notes.length; i++)
  for (int j = 0; j < notes[i].length; j++) {
    if (notes[i][j].equals(sym)) {
        return Character.getNumericValue(oct) * 12 + i;
    }
  }

  // If nothing was found, we return -1.
  return -1;
}

关于java - 将音符字符串转换为MIDI音高数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35690046/

10-10 22:35