diff --git a/src/components/audio-feedback.js b/src/components/audio-feedback.js index cdae3ef89a7b42c4745e2227a08836bc5388380b..71798ba4e05f81398f73942176fa1a94671bfef6 100644 --- a/src/components/audio-feedback.js +++ b/src/components/audio-feedback.js @@ -8,11 +8,12 @@ AFRAME.registerComponent("networked-audio-analyser", { this.volume = 0; this.prevVolume = 0; this.smoothing = 0.3; + this.threshold = 0.01; this.el.addEventListener("sound-source-set", event => { const ctx = THREE.AudioContext.getContext(); this.analyser = ctx.createAnalyser(); this.analyser.fftSize = 32; - this.levels = new Float32Array(this.analyser.frequencyBinCount); + this.levels = new Uint8Array(this.analyser.frequencyBinCount); event.detail.soundSource.connect(this.analyser); }); }, @@ -20,14 +21,19 @@ AFRAME.registerComponent("networked-audio-analyser", { tick: function() { if (!this.analyser) return; - this.analyser.getFloatTimeDomainData(this.levels); + // take care with compatibility, e.g. safari doesn't support getFloatTimeDomainData + this.analyser.getByteTimeDomainData(this.levels); let sum = 0; for (let i = 0; i < this.levels.length; i++) { - const amplitude = this.levels[i]; + const amplitude = (this.levels[i] - 128) / 128; sum += amplitude * amplitude; } - this.volume = this.smoothing * Math.sqrt(sum / this.levels.length) + (1 - this.smoothing) * this.prevVolume; + let currVolume = Math.sqrt(sum / this.levels.length); + if (currVolume < this.threshold) { + currVolume = 0; + } + this.volume = this.smoothing * currVolume + (1 - this.smoothing) * this.prevVolume; this.prevVolume = this.volume; } });