Skip to content

Instantly share code, notes, and snippets.

@suneo3476
Last active April 22, 2019 10:48
Show Gist options
  • Save suneo3476/5475dd5eabf72196b63f93ebb940a29a to your computer and use it in GitHub Desktop.
Save suneo3476/5475dd5eabf72196b63f93ebb940a29a to your computer and use it in GitHub Desktop.
周波数に最も近い音を求めるやつ 入力:周波数f 出力:周波数に最も近い西洋音階 Scale・88鍵ピアノの低い側から数えた高さ Octave
var reader = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
reader.on('line', function (line) {
// 入力:周波数
const f = Number(line);
// 88鍵ピアノ最低音のラから1オクターブ分の周波数
const baseScale = [
[27.500,'ラ'],
[29.135,'ラ#'],
[30.868,'シ'],
[32.703,'ド'],
[34.648,'ド#'],
[36.708,'レ'],
[38.891,'レ#'],
[41.203,'ミ'],
[43.654,'ファ'],
[46.249,'ファ#'],
[48.999,'ソ'],
[51.913,'ソ#']
];
let scale;
let octave;
let octaves = [];
let minQ = 1245;
let minIndex;
baseScale.forEach(function(current, index, array){
// 入力周波数と配列の周波数の余剰=音階
const q = f % current[0];
//余剰が最小になる音階が最も近い
if ( minQ > q ) {
minQ = q
minIndex = index;
}
// 入力周波数と直前の商の、底が2の対数=高さ
octaves.push(Math.log2(f / current[0]));
})
// 出力:音階
scale = baseScale[minIndex][1];
// 出力:高さ
octave = Math.round(octaves[minIndex]+1);
console.log("周波数f:" + f + "Hz に最も近い音階と高さは……");
console.log("ピアノで低い方から " + octave + " 番目の「" + scale + "」です!");
});
process.on('SIGINT', function() {
console.log('Ctrl+C!!');
process.exit(0);
});
process.on('exit', function () {
console.log('EXIT!');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment