btrtracks/public/visuals.js

84 lines
1.8 KiB
JavaScript
Raw Normal View History

2018-12-01 22:46:03 +00:00
(function () {
var audio = document.querySelector('#player')
var canvas = document.querySelector('#visualizer')
var playbar = document.querySelector('.playing-bar')
2020-09-25 14:50:56 +00:00
var ctx = canvas.getContext('2d')
2018-12-01 22:46:03 +00:00
2020-09-25 14:50:56 +00:00
var context
var src
var analyser
2018-12-01 22:46:03 +00:00
2020-09-25 14:50:56 +00:00
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()
}
2018-12-01 22:46:03 +00:00
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)
2020-09-25 14:50:56 +00:00
const realAdjusted = barHeight * (HEIGHT / analyser.fftSize)
2018-12-01 22:46:03 +00:00
ctx.fillStyle = 'rgb(' + r + ',' + g + ',' + b + ')'
ctx.fillRect(x, HEIGHT - realAdjusted, barWidth, realAdjusted)
x += barWidth + 1
}
}
window.addEventListener('resize', convenientSizer)
2020-09-25 14:50:56 +00:00
window.resumeAnalyzer = function () {
if (!context) start()
return context
}
2018-12-01 22:46:03 +00:00
convenientSizer()
})()