audio-vis/raw/javascript/audio.js
versustunez 9d5259767c - added imageUploader
- fixed loading songs
- cleanup utils
- added some helper class
- cleanup preparing of WEBGL2
- added 3D wave
- added light-support
- added configs
- added gui-events for playing, shuffling and playlist
2020-08-05 11:24:59 +02:00

75 lines
2 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(src) {
let self = this;
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 => {
window.dispatchEvent(new CustomEvent('playSong'));
}).catch(e => {
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;
}
}