visualizer

This commit is contained in:
iou1name 2024-12-28 19:37:15 -05:00
parent 8238288df6
commit 3f9048a395
3 changed files with 46 additions and 1 deletions

View File

@ -94,6 +94,11 @@ img {
grid-area: B;
}
#visualizer {
width: 90%;
height: 4em;
}
#player_controls {
grid-area: C;
}

View File

@ -1,11 +1,14 @@
var player;
var pos_int;
var canvasCtx;
var audioCtx;
var analyser;
var audio_data;
var draw_loop;
var vol_prev;
function init() {
player = document.querySelector('#player');
canvasCtx = document.querySelector('#visualizer').getContext('2d');
player.addEventListener('ended', nextTrack);
player.addEventListener('loadedmetadata', display_duration);
@ -62,6 +65,10 @@ async function playTrack() {
player.play();
navigator.mediaSession.playbackState = "playing";
if (!audioCtx) {
init_analyzer();
}
document.querySelector("#play-btn").style.display = "none";
document.querySelector("#pause-btn").style.display = "initial";
}
@ -93,6 +100,7 @@ function setMediaSession(track) {
}
function update_now_playing(track) {
track.artwork.pop(1); // remove lower resolution option
document.querySelector('#now_playing_artist').textContent = track.artist;
document.querySelector('#now_playing_album').textContent = track.album;
document.querySelector('#now_playing_title').textContent = track.title;
@ -160,5 +168,36 @@ function init_analyzer() {
source.connect(analyser);
source.connect(audioCtx.destination);
analyser.fftSize = 256;
analyser.minDecibels = -90;
analyser.maxDecibels = -10;
analyser.smoothingTimeConstant = 0.85;
audio_data = new Uint8Array(analyser.frequencyBinCount);
let canvas = document.querySelector('#visualizer');
canvasCtx.clearRect(0, 0, canvas.width, canvas.height);
draw();
}
function draw() {
draw_loop = requestAnimationFrame(draw);
analyser.getByteTimeDomainData(audio_data);
let canvas = document.querySelector('#visualizer');
canvasCtx.fillStyle = "rgb(0 0 0)";
canvasCtx.fillRect(0, 0, canvas.width, canvas.height);
const barWidth = (canvas.width / analyser.frequencyBinCount) * 2.5;
let barHeight;
let x = 0;
for (let i = 0; i < analyser.frequencyBinCount; i++) {
barHeight = audio_data[i];
canvasCtx.fillStyle = `rgb(${barHeight + 100} 50 50)`;
canvasCtx.fillRect(x, canvas.height - barHeight, barWidth, barHeight);
x += barWidth + 1;
}
}

View File

@ -31,6 +31,7 @@
<div id="title">
<h4><span id="now_playing_artist">Artist</span> - <span id="now_playing_album">Album</span></h4>
<h3 id="now_playing_title">Title</h3>
<canvas id="visualizer" height="300" width="1000"></canvas>
</div>
<div id="player_controls">
<audio id="player" style="display:none"></audio>