const urlParams = new URLSearchParams(window.location.search); const currentSide = urlParams.get("side"); const Cassette = new Audio(`audio/2019-mix-side-${currentSide}.mp3`); let TapeDeck = { elem: document.getElementById("tape-deck"), notes: document.getElementById("notes"), trackData: [], currentTrackIndex: 0, hasStarted: false, isPlaying: false, images: { stop: "images/cool-deck.png", go: "images/cool-deck.gif" }, go: function () { this.elem.src = this.images.go; this.isPlaying = true; }, stop: function () { this.elem.src = this.images.stop; this.isPlaying = false; }, playButton: { elem: document.getElementById("play-button"), state: "off", up: "images/play-button-up.png", down: "images/play-button-down.png", initSound: new Audio("audio/tape-start.mp3"), pressSound: new Audio("audio/button-press.mp3"), toggle: function () { if (this.state === "off") { this.elem.src = this.down; this.state = "on"; } else { this.elem.src = this.up; this.state = "off"; } } } }; function start() { const btn = TapeDeck.playButton; TapeDeck.hasStarted = true; btn.toggle(); btn.initSound.onended = (event) => { Cassette.play(); }; btn.initSound.play(); } function pause() { const btn = TapeDeck.playButton; btn.toggle(); btn.pressSound.play(); Cassette.pause(); TapeDeck.stop(); } function resume() { const btn = TapeDeck.playButton; btn.pressSound.play(); btn.toggle(); Cassette.play(); } // button onclick points here function play() { if (TapeDeck.isPlaying) { pause(); return; } TapeDeck.hasStarted ? resume() : start(); TapeDeck.go(); } function reset() { Cassette.currentTime = 0; } function isLastTrack(current, tracks) { return current + 1 === tracks.length; } function getTrack(time) { const { currentTrackIndex, trackData } = TapeDeck; const nextIndex = currentTrackIndex + 1; const startTimes = trackData.map( t => t.start ); if (isLastTrack(currentTrackIndex, startTimes)) { return trackData[trackData.length - 1]; } else { if (time >= startTimes[nextIndex]) { TapeDeck.currentTrackIndex = nextIndex; } return trackData[currentTrackIndex]; } } function formatTrackData(track) { let string = `${track.title} - ${track.artist}`; if (track.album) { string = string.concat(` - ${track.album}`); } if (track.link) { string = string.concat(` - ${track.link}`) } return string; } function loadTrackData() { fetch(`side${currentSide}.json`) .then(response => response.json()) .then((data) => { TapeDeck.trackData = data; }); } function resumeMaybe() { if (localStorage.getItem(currentSide)) { Cassette.currentTime = localStorage.getItem(currentSide); } } loadTrackData(); resumeMaybe(); Cassette.addEventListener("timeupdate", (event) => { const time = Cassette.currentTime; const currentTrack = getTrack(time); localStorage.setItem(currentSide, time); if (!currentTrack) return; TapeDeck.notes.textContent = formatTrackData(currentTrack); });