Given a midi pitch value (0-127), give back the musical note. - Java javax.sound.midi

Java examples for javax.sound.midi:MidiSystem

Description

Given a midi pitch value (0-127), give back the musical note.

Demo Code


//package com.java2s;

public class Main {
    /**/*from   w w w  .  j  a  v a  2 s.  c om*/
     * Given a midi pitch value (0-127), give back the musical note.
     */
    public static String getNoteFromValue(int value) {
        if (value > 127 || value < 0) {
            System.out.println("value is out of range");
            System.exit(1);
        }

        int octave = -100;

        octave = (int) Math.floor(value / 12) - 1;

        //System.out.println("octave: " + octave);

        int noteValue = value - ((octave + 1) * 12);

        //System.out.println("noteValue: " + noteValue);

        String note = "";

        switch (noteValue) {
        case 0:
            note = "C";
            break;
        case 1:
            note = "C#";
            break;
        case 2:
            note = "D";
            break;
        case 3:
            note = "D#";
            break;
        case 4:
            note = "E";
            break;
        case 5:
            note = "F";
            break;
        case 6:
            note = "F#";
            break;
        case 7:
            note = "G";
            break;
        case 8:
            note = "G#";
            break;
        case 9:
            note = "A";
            break;
        case 10:
            note = "A#";
            break;
        case 11:
            note = "B";
            break;
        }

        return note + octave;
    }
}

Related Tutorials