Skip to content

Instantly share code, notes, and snippets.

@YuxiUx
Last active May 20, 2023 07:09
Show Gist options
  • Save YuxiUx/ef84328d95b10d0fcbf537de77b936cd to your computer and use it in GitHub Desktop.
Save YuxiUx/ef84328d95b10d0fcbf537de77b936cd to your computer and use it in GitHub Desktop.
How to convert midi note to frequency in C, C++, Python, JS and PHP

JS

function noteToFreq(note) {
    let a = 440; //frequency of A (coomon value is 440Hz)
    return (a / 32) * (2 ** ((note - 9) / 12));
}

PHP

function noteToFreq($note) {
    $a = 440; //frequency of A (coomon value is 440Hz)
    return ($a / 32) * (2 ** (($note - 9) / 12));
}

python 3

def noteToFreq(note):
    a = 440 #frequency of A (coomon value is 440Hz)
    return (a / 32) * (2 ** ((note - 9) / 12))

c / c++

#include <math.h> //<cmath> in case of c++

float noteToFreq(int note) {
    float a = 440; //frequency of A (coomon value is 440Hz)
    return (a / 32) * pow(2, ((note - 9) / 12.0));
}
@6r1d
Copy link

6r1d commented Dec 19, 2020

Thanks!

@ljleb
Copy link

ljleb commented Apr 4, 2021

I believe in c/c++ the type of a / 32 is int. In other words, the floating point part is lost before the result of the expression is multiplied with pow(...).

@YuxiUx
Copy link
Author

YuxiUx commented Apr 18, 2021

I believe in c/c++ the type of a / 32 is int. In other words, the floating point part is lost before the result of the expression is multiplied with pow(...).

Yes, that's true. honestly c version was "automatically" generated without even attempt of compiling it.. and that was a mistake.
thanks for you comment should be fixed including second similar error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment