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; this.playButton.toggle(); }, start: function () { this.hasStarted = true; this.playButton.initSound.onended = (event) => { Cassette.play(); }; this.playButton.initSound.play(); this.go(); }, pause: function () { this.playButton.toggle(); this.playButton.pressSound.play(); Cassette.pause(); this.elem.src = this.images.stop; this.isPlaying = false; }, resume: function () { this.playButton.pressSound.play(); this.go(); Cassette.play(); }, 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"; } } } }; // button onclick points here function play() { if (TapeDeck.isPlaying) { TapeDeck.pause(); return; } TapeDeck.hasStarted ? TapeDeck.resume() : TapeDeck.start(); } 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); });