audio-vis/raw/javascript/audio.js

71 lines
1.8 KiB
JavaScript
Raw Normal View History

2020-08-01 21:51:54 +02:00
const AudioContext = window.AudioContext || window.webkitAudioContext;
2020-04-07 21:44:46 +02:00
class AudioHandler {
async init() {
2020-08-01 21:51:54 +02:00
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();
}
this.audioFile.play();
}
getIntArray(steps) {
let dataArray = new Uint8Array(steps);
this.analyser.getByteFrequencyData(dataArray);
return dataArray;
}
getFloatArray() {
let dataArray = new Float32Array(this.analyser.frequencyBinCount);
this.analyser.getFloatTimeDomainData(dataArray);
return dataArray;
2020-04-07 21:44:46 +02:00
}
}