xxxxxxxxxx
81
const trackId = '17i5jLpzndlQhbS4SrTd0B';
const accessToken = 'BQCgaMNswWFl1ahgtcWBLj9RU7WtFRrE71p11EagSRy2iQaS_OwgZx-jaMCJBFmzZFYuVYF4vwPOkdCGkwW_OBQdDDmTXL675oDrS950vdODwTaosCw';
let songParams;
const drawingWidth = 1000;
const drawingHeight = 400; // Height for the vertical lines
const canvasWidth = 1500;
const canvasHeight = 1400; // Total canvas height
function getTrackParams(trackId) {
const requestOptions = {
method: 'GET',
headers: { 'Authorization': `Bearer ${accessToken}` },
};
fetch(`https://api.spotify.com/v1/audio-analysis/${trackId}`, requestOptions)
.then(data => data.json())
.then((data) => {
songParams.analysis = data;
console.log(data);
redraw();
});
fetch(`https://api.spotify.com/v1/audio-features/${trackId}`, requestOptions)
.then(data => data.json())
.then((data) => {
songParams.features = data;
console.log(data);
redraw();
});
fetch(`https://api.spotify.com/v1/tracks/${trackId}`, requestOptions)
.then(data => data.json())
.then((data) => {
songParams.trackInfo = data;
console.log(data);
redraw();
});
}
function setup() {
songParams = {};
getTrackParams(trackId);
createCanvas(canvasWidth, canvasHeight);
colorMode(HSL, 360, 100, 100);
noLoop(); // Static drawing, call 'redraw()' in the console to refresh
}
function draw() {
background(0);
if (!songParams.analysis || !songParams.features) return;
let totalDuration = songParams.analysis.track.duration;
let centerX = (canvasWidth - drawingWidth) / 2;
let centerY = (canvasHeight - drawingHeight) / 2;
// Draw vertical lines for each segment
songParams.analysis.segments.forEach((segment) => {
let x = map(segment.start, 0, totalDuration, centerX, centerX + drawingWidth);
let lineWidth = map(segment.duration, 0, totalDuration, 0, drawingWidth);
let loudness = segment.loudness_max;
let lineHeight = map(loudness, -60, 0, 0, drawingHeight);
stroke(255); // White color for lines
strokeWeight(lineWidth);
line(x, centerY + (drawingHeight / 2) - lineHeight / 2, x, centerY + (drawingHeight / 2) + lineHeight / 2);
});
// Write the song name and artist names below the vertical lines
fill(255);
strokeWeight(0);
textAlign(CENTER);
textSize(24);
textStyle(BOLD);
text(songParams.trackInfo.name, canvasWidth / 2, centerY + drawingHeight + 50);
textSize(18);
textStyle(NORMAL);
let artistNames = songParams.trackInfo.artists.map(artist => artist.name).join(', ');
text(artistNames, canvasWidth / 2, centerY + drawingHeight + 80);
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}