btrtracks/public/visuals.js

84 lines
1.8 KiB
JavaScript

(function () {
var audio = document.querySelector('#player')
var canvas = document.querySelector('#visualizer')
var playbar = document.querySelector('.playing-bar')
var ctx = canvas.getContext('2d')
var context
var src
var analyser
var bufferLength
var dataArray
var barHeight
var x = 0
function start () {
context = new AudioContext()
src = context.createMediaElementSource(audio)
analyser = context.createAnalyser()
src.connect(analyser)
analyser.connect(context.destination)
analyser.fftSize = 256
bufferLength = analyser.frequencyBinCount
dataArray = new Uint8Array(bufferLength)
if (!analyser.getByteFrequencyData) {
console.error('This browser sucks. No visualizer for you :(')
return
}
renderFrame()
}
var WIDTH = canvas.width
var HEIGHT = canvas.height
var barWidth
function convenientSizer () {
canvas.width = playbar.clientWidth
canvas.height = 40
WIDTH = canvas.width
HEIGHT = canvas.height
}
function renderFrame () {
requestAnimationFrame(renderFrame)
barWidth = (WIDTH / bufferLength) * 2.5
x = 0
analyser.getByteFrequencyData(dataArray)
ctx.clearRect(0, 0, WIDTH, HEIGHT)
for (var i = 0; i < bufferLength; i++) {
barHeight = dataArray[i]
var r = 50
var g = barHeight + (i / bufferLength)
var b = 250 * (i / bufferLength)
const realAdjusted = barHeight * (HEIGHT / analyser.fftSize)
ctx.fillStyle = 'rgb(' + r + ',' + g + ',' + b + ')'
ctx.fillRect(x, HEIGHT - realAdjusted, barWidth, realAdjusted)
x += barWidth + 1
}
}
window.addEventListener('resize', convenientSizer)
window.resumeAnalyzer = function () {
if (!context) start()
return context
}
convenientSizer()
})()