audio-vis/raw/javascript/audio.js

84 lines
2.5 KiB
JavaScript

const AudioContext = window.AudioContext || window.webkitAudioContext;
class AudioHandler {
async init() {
let self = this;
self.isStarted = false;
self.audioFile = new Audio();
self.actx = new AudioContext();
self.analyser = self.actx.createAnalyser();
self.analyser.fftSize = 4096;
self.lastSong = null;
await self.connectAll();
}
async connectAll() {
let self = this;
self.source = self.actx.createMediaElementSource(self.audioFile);
self.source.connect(self.analyser);
self.analyser.connect(self.actx.destination);
self.audioFile.addEventListener('ended', player.nextSong.bind(player));
}
async start() {
if (this.audioFile.src === '') {
return;
}
if (!this.isStarted) {
this.isStarted = true;
await this.actx.resume();
}
}
async stop() {
if (this.isStarted) {
this.isStarted = false;
await this.actx.suspend();
}
}
fftSize(size) {
this.analyser.fftSize = size;
}
smoothing(float) {
this.analyser.smoothingTimeConstant = float;
}
loadSong(file) {
if (!file) {
NotificationHandler.createNotification("Sorry!<br> Currently no Song is uploaded!", "error", 2000);
return false;
}
let self = this,
src = file.file;
if (self.lastSong) {
URL.revokeObjectURL(self.lastSong);
}
self.lastSong = this.audioFile.src = URL.createObjectURL(src);
if (!this.isStarted) {
this.start().catch(alert);
}
this.audioFile.play().then(e => {
if (pConf.get("showPlaying", "true")) {
NotificationHandler.createNotification("<span class='now-playing'>Now Playing:</span>" + file.getAudioName(), "info", pConf.get("showPlayingTime", 1000));
}
window.dispatchEvent(new CustomEvent('playSong'));
}).catch(e => {
NotificationHandler.createNotification(e.message, "error", 1000);
player.nextSong();
});
}
getIntArray(steps) {
let dataArray = new Uint8Array(steps);
this.analyser.getByteFrequencyData(dataArray);
return dataArray;
}
getFloatArray() {
let dataArray = new Float32Array(this.analyser.fftSize);
this.analyser.getFloatTimeDomainData(dataArray);
return dataArray;
}
}