From a5b5cce4938f8acd73ca2d8e73c9e9ad9492fbba Mon Sep 17 00:00:00 2001 From: "J. David Lee" Date: Mon, 2 Dec 2019 20:47:40 +0100 Subject: [PATCH] util: Convert midi note to frequency. --- lib/util/notefreq.go | 8 ++++++++ lib/util/notefreq_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 lib/util/notefreq.go create mode 100644 lib/util/notefreq_test.go diff --git a/lib/util/notefreq.go b/lib/util/notefreq.go new file mode 100644 index 0000000..9f85cd0 --- /dev/null +++ b/lib/util/notefreq.go @@ -0,0 +1,8 @@ +package util + +import "math" + +// Return the frequency of a given MIDI note number. +func NoteFreq(n int) float64 { + return (math.Pow(2, (float64(n)-69)/12)) * 440 +} diff --git a/lib/util/notefreq_test.go b/lib/util/notefreq_test.go new file mode 100644 index 0000000..8e3bac6 --- /dev/null +++ b/lib/util/notefreq_test.go @@ -0,0 +1,31 @@ +package util + +import ( + "fmt" + "testing" +) + +func TestNoteFreq(t *testing.T) { + type TestCase struct { + In int + Out float64 + } + + testCases := []TestCase{ + {108, 4186.01}, + {81, 880}, + {69, 440}, + {58, 233.08}, + {57, 220}, + {56, 207.65}, + {55, 196}, + {36, 65.41}, + } + + for _, tc := range testCases { + out := NoteFreq(tc.In) + if fmt.Sprintf("%.2f", out) != fmt.Sprintf("%.2f", tc.Out) { + t.Fatalf("%v != %v", out, tc.Out) + } + } +}