btrtracks/public/visuals.js

70 lines
1.5 KiB
JavaScript

(function () {
var audio = document.querySelector('#player')
var canvas = document.querySelector('#visualizer')
var playbar = document.querySelector('.playing-bar')
var context = new AudioContext()
var src = context.createMediaElementSource(audio)
var analyser = context.createAnalyser()
var ctx = canvas.getContext('2d')
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
}
src.connect(analyser)
analyser.connect(context.destination)
analyser.fftSize = 256
var bufferLength = analyser.frequencyBinCount
var dataArray = new Uint8Array(bufferLength)
var barHeight
var x = 0
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)
let realAdjusted = barHeight * (HEIGHT / analyser.fftSize)
ctx.fillStyle = 'rgb(' + r + ',' + g + ',' + b + ')'
ctx.fillRect(x, HEIGHT - realAdjusted, barWidth, realAdjusted)
x += barWidth + 1
}
}
renderFrame()
window.addEventListener('resize', convenientSizer)
window.attachAudioContext(context)
convenientSizer()
})()