Java examples for javax.sound.midi:MidiSystem
Converts a note name in scientific pitch notation into its MIDI number
//package com.java2s; import java.util.HashMap; import java.util.Map; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { private static final Map<String, Integer> _baseMap = new HashMap<>(); private static final Pattern NOTE_FORMAT = Pattern .compile("([A-G])([#b]?)(-?\\d{1,2})"); /**//from ww w . j ava 2s . c o m * Converts a note name in scientific pitch notation into its MIDI number * @param noteName - the name of the note in scientific pitch notation * (e.g., A4, C#3, Gb5) * @return the MIDI number of the given note */ public static int noteNameToNumber(String noteName) { final Matcher matcher = NOTE_FORMAT.matcher(noteName); if (!matcher.matches()) throw new IllegalArgumentException( "Given note name didn't match pattern"); final MatchResult result = matcher.toMatchResult(); final String pitchClass = result.group(1); final String sharpFlat = result.group(2); final int octave = Integer.parseInt(result.group(3)); final int accidental; if (sharpFlat.isEmpty()) accidental = 0; else if (sharpFlat.charAt(0) == 'b') accidental = -1; else accidental = 1; return _baseMap.get(pitchClass).intValue() + accidental + (12 * (octave + 1)); } }