@pedroloch/tuner
Version:
A javascript library to create a chromatic tuner that uses the ml5 pitch detection algorithm.
75 lines (74 loc) • 2.73 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import ml5 from 'ml5';
import { on, trigger } from './events';
import { getNote } from './helpers';
const modelUrl = 'https://cdn.jsdelivr.net/gh/ml5js/ml5-data-and-models/models/pitch-detection/crepe/';
const createTuner = () => {
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
let pitch = 0;
let loaded = false;
let isOn = false;
let pitchDetector;
let mic;
function setup() {
return __awaiter(this, void 0, void 0, function* () {
mic = yield navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: false,
noiseSuppression: false,
autoGainControl: false,
},
});
startPitch(mic, audioContext);
});
}
function startPitch(mic, audioContext) {
audioContext = new AudioContext();
pitchDetector = ml5.pitchDetection(modelUrl, audioContext, mic, () => {
loaded = true;
getPitch();
});
}
function getPitch() {
pitchDetector.getPitch(function (err, frequency) {
if (err)
throw new Error(err.message);
if (isOn) {
if (frequency) {
const { pitch, note, diff } = getNote(frequency);
trigger({
frequency,
pitch,
note,
diff,
});
}
setTimeout(() => {
getPitch();
}, 100);
}
});
}
function start() {
return __awaiter(this, void 0, void 0, function* () {
yield setup();
if (pitchDetector)
getPitch();
isOn = true;
});
}
function stop() {
isOn = false;
mic.getTracks().forEach((t) => t.stop());
}
return { start, stop, getData: on, isOn };
};
export default createTuner;