58 lines
2 KiB
C#
58 lines
2 KiB
C#
using System;
|
|
|
|
namespace JD.Serialization
|
|
{
|
|
/// <summary>
|
|
/// Some MIDI utilities
|
|
/// </summary>
|
|
public static class MidiUtils
|
|
{
|
|
private static readonly string[] _noteNames = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
|
|
|
|
/// <summary>
|
|
/// Returns a frequency from a midi note
|
|
/// (see http://www.phys.unsw.edu.au/jw/notes.html)
|
|
/// </summary>
|
|
/// <param name="midiNote">the midi note to convert</param>
|
|
/// <returns>a frequency</returns>
|
|
public static float MidiToFrequency(int midiNote)
|
|
{
|
|
return (440.0f / 32.0f) * (float)Math.Pow(2, ((midiNote - 9) / 12.0f));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns a midi note from a frequency
|
|
/// (see http://www.phys.unsw.edu.au/jw/notes.html)
|
|
/// </summary>
|
|
/// <param name="frequency">the frequency to convert</param>
|
|
/// <returns>a midi note</returns>
|
|
public static int FrequencyToMidi(float frequency)
|
|
{
|
|
return frequency > 0 ? (int)(12.0 * Math.Log(frequency / 440.0, 2) + 69.0 + 0.5) : 0;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the name of a midi note (C#3, D4...)
|
|
/// using standard naming conventions
|
|
/// </summary>
|
|
/// <param name="midiNote">a midi note</param>
|
|
/// <returns>a midi note name</returns>
|
|
public static string MidiNoteName(int midiNote)
|
|
{
|
|
int octave = (midiNote / 12) - 2;
|
|
int index = (midiNote % 12);
|
|
return $"{_noteNames[index]}{octave}";
|
|
}
|
|
|
|
/// <summary>
|
|
/// Indicates whether a midi note is sharp
|
|
/// </summary>
|
|
/// <param name="midiNote">a midi note</param>
|
|
/// <returns>the "sharpness" of the note</returns>
|
|
public static bool IsMidiNoteSharp(int midiNote)
|
|
{
|
|
var mod12 = midiNote % 12;
|
|
return mod12 == 1 || mod12 == 3 || mod12 == 6 || mod12 == 8 || mod12 == 10;
|
|
}
|
|
}
|
|
}
|