Skip to content

Instantly share code, notes, and snippets.

@robksawyer
Created September 25, 2020 11:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robksawyer/ee9ca47d81156d08acb0b2057c2ef653 to your computer and use it in GitHub Desktop.
Save robksawyer/ee9ca47d81156d08acb0b2057c2ef653 to your computer and use it in GitHub Desktop.
Code for an animated audio toggle.
Class((function SoundIcon() {
Inherit(this, Element);
const _this = this,
$this = _this.element,
_bars = [];
var _audioCtrl, _analyser, _analyserArray;
const RANGE = [255, 100, 140];
function hover({
action: action
}) {
$this.tween({
opacity: "over" === action ? .5 : 1
}, 300, "easeOutCubic")
}
function click() {
Track.event("header", "click", "sound", AudioController.instance().isMuted ? "unmute" : "mute"), AudioController.instance().toggleSound(AudioController.instance().isMuted)
}
function loop() {
_analyser.getByteFrequencyData(_analyserArray);
let count = 0,
indexes = 0,
avg = [];
for (let i = 0, l = 60; i < l; i++) count += _analyserArray[i], indexes++;
avg.push(count / indexes), count = 0, indexes = 0;
for (let i = 40, l = 200; i < l; i++) count += _analyserArray[i], indexes++;
avg.push(count / 300), count = 0, indexes = 0;
for (let i = 150, l = 500; i < l; i++) count += _analyserArray[i], indexes++;
avg.push(count / 300);
for (let i = 0, l = avg.length; i < l; i++) {
if (isNaN(avg[i]) || !avg[i]) continue;
let scale = TweenManager.Interpolation.Cubic.In(Math.range(avg[i], 0, .9 * RANGE[i], .2, 1, !0)),
$bar = _bars[i];
AudioController.instance().isMuted && (scale = .2), $bar.targetScale = scale, $bar.currentScale += .2 * ($bar.targetScale - $bar.currentScale), $bar.div.style.transform = `scaleY(${$bar.currentScale})`
}
}!async function () {
_this.label = "sound", _this.element.label = "sound",
function initHTML() {
$this.css({
position: "relative",
whiteSpace: "nowrap"
});
for (let i = 0, l = 3; i < l; i++) {
let $bar = $this.create("bar");
$bar.css({
display: "inline-block",
position: "relative",
width: 2,
height: 25,
marginLeft: 0 === i ? 0 : 4,
backgroundColor: "#ffffff",
transform: "scaleY(0.3)"
}), $bar.transform({
scaleY: .3
}), $bar.currentScale = .3, $bar.targetScale = _bars.currentScale, _bars.push($bar)
}
}(), $this.interact(hover, click), await async function initAudio() {
_analyserArray = new Uint8Array(2048), _audioCtrl = AudioController.instance(), _analyser = await _audioCtrl.getAnalyser("main")
}(), _this.startRender(loop)
}(), _this.hover = hover, _this.click = click, _this.updateColor = function (color) {
_bars.forEach($bar => {
$bar.tween({
backgroundColor: color
}, 300, "easeOutCubic")
})
}
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment