chiro-canto/public/larynx/scripts/spectro.js

91 lines
2.8 KiB
JavaScript
Raw Normal View History

2021-04-07 12:35:25 +02:00
'use strict';
let audio = document.getElementById('audio');
let file_path = audio.src;
2021-04-07 13:17:37 +02:00
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', '/larynx/scripts/hot-colormap.json', true); // Replace 'appDataServices' with the path to your file
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
let colorMap;
let wavesurfer;
2021-04-07 12:35:25 +02:00
// Init & load
2021-04-07 13:17:37 +02:00
function initAndLoadSpectrogram(colorMap) {
2021-04-07 12:35:25 +02:00
// Create an instance
var options = {
container: '#waveform',
waveColor: 'white',
progressColor: 'purple',
loaderColor: 'purple',
cursorColor: 'navy',
plugins: [
WaveSurfer.spectrogram.create({
wavesurfer: wavesurfer,
container: "#wave-spectrogram",
2021-04-07 13:17:37 +02:00
labels: true,
colorMap: colorMap
2021-04-07 12:35:25 +02:00
})
]
};
wavesurfer = WaveSurfer.create(options);
wavesurfer.load(file_path);
2021-04-07 13:17:37 +02:00
}
2021-04-07 12:35:25 +02:00
let play = document.getElementById('play').addEventListener('click', function() {
wavesurfer.play();
});
let pause = document.getElementById('pause').addEventListener('click', function() {
wavesurfer.pause();
});
let restart = document.getElementById('restart').addEventListener('click', function() {
wavesurfer.play(0);
});
function getCursorXY(e) {
return [e.pageX, e.pageY];
}
function measure(x, y) {
let spectro = document.getElementById('wave-spectrogram');
let spectro_x = spectro.offsetLeft;
let spectro_y = spectro.offsetTop;
let spectro_height = spectro.clientHeight;
let spectro_width = spectro.clientWidth;
x = (x - spectro_x);
y = -(-(-y + spectro_y) - spectro_height);
let t = (x / spectro_width) * audio.duration;
let f = (y / spectro_height) * 24;
document.getElementById('cursor-time').innerHTML = Math.round(t);
document.getElementById('cursor-frequency').innerHTML = Math.round(f);
}
let spectro = document.getElementById("wave-spectrogram");
console.log(spectro);
spectro.addEventListener('mousemove', function() {
let coords = getCursorXY(window.event);
measure(coords[0], coords[1]);
// console.log(getCursorXY(window.event));
2021-04-07 13:17:37 +02:00
});
document.addEventListener('DOMContentLoaded', function() {
// Load a colormap json file to be passed to the spectrogram.create method.
WaveSurfer.util
.fetchFile({
url: '/larynx/scripts/hot-colormap.json',
responseType: 'json'
})
.on('success', colorMap => {
initAndLoadSpectrogram(colorMap);
});
2021-04-07 12:35:25 +02:00
});