# Convert octave to pitch

I have some mallet sounds when a user types (in the key of A Major), and i need to transpose it based off what song is playing in the background (for example a song in C Major needs to go up 3 semi-tones or half-steps)

An octave means that the ratio between two frequences is 2:1 (e.g. pitch for one octave higher is 2, for 2 = 4, etc.), so the pitch becomes:

``````pitch = 2 ** octaves;
``````

Say, you have 12 semitones in an octave, then it becomes:

``````pitch = 2 ** (semitones / 12);
``````

For an absolute pitch, like F4, you can represent it as a MIDI note 64 (you can google those). So, in the end, if you want to find a pitch of MIDI note C4 (60) using a sample of MIDI note D4 (62), it becomes:

``````// 2 ** ((D4 - C4) / 12);
pitch = 2 ** ((62 - 60) / 12);
``````

If you need cents for say vibrato, you can divide semitone accordingly - there are 100 cents in semitone:

``````// 10 cents = 0.1 semitones
const D4 = 62 + 10 / 100;
pitch = 2 ** ((D4 - 60) / 12);
``````

Hope that helps.

3 Likes

I have also solved it in this way! I needed to be able to transpose a note up from like A to C for example, and notes in a scale are not equally divided into 12 even though there are 12 notes in a scale. Its all about the ratios!

with this chart: C5S1_Intervals
you can see the ratios of each note in a chromatic scale compared to the input note. Here is a function to transpose up. So if you are playing an A note in a soundSlot but you want it to play a C you could do

``````soundSlot.pitch = this.transposeUpSemiTones(3)
soundSlot.play

``````

With the transpose function being:

``````AudioController.prototype.transposeUpSemiTones = function(semitones){
if (newKey == 0){
return 1;
}
else if (newKey == 1){
return 16/15;
}
else if (newKey == 2){
return 9/8;
}
else if (newKey == 3){
return 6/5;
}
else if (newKey == 4){
return 5/4;
}
else if (newKey == 5){
return 4/3;
}
else if (newKey == 6){
return 45/32;
}
else if (newKey == 7){
return 3/2;
}
else if (newKey == 8){
return 8/5;
}
else if (newKey == 9){
return 5/3;
}
else if (newKey == 10){
return 9/5;
}
else if (newKey == 11){
return 15/8;
}
return 1; //Not specified
};
``````
1 Like