summaryrefslogtreecommitdiff
path: root/tape-deck.js
blob: 14ed83f8c832f5ed428b171d77003269bf5c5390 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const urlParams = new URLSearchParams(window.location.search);
const currentSide = urlParams.get("side");
const tape = new Audio(`audio/2019-mix-side-${currentSide}.ogg`);

const pressPlaySound = new Audio("audio/tape-start.mp3");
pressPlaySound.onended = (event) => {
    tape.play();
}


let deck = document.getElementById("tape-deck");
let notes = document.getElementById("notes");
let currentTrackIndex = 0;
let hasStarted = false;

function play() {
    fetch(`side${currentSide}.json`)
        .then(response => response.json())
        .then((trackData) => {
            if (!hasStarted) {
                pressPlaySound.play();
                hasStarted = true;
                deck.src = "images/cool-deck.gif"

                tape.addEventListener("timeupdate", (event) => {
                    const time = tape.currentTime;
                    const currentTrack = getTrack(time, currentTrackIndex, trackData);
                    notes.textContent = currentTrack.title;
                });
            } else {
                tape.play();
                deck.src = "images/cool-deck.gif"
            }
        });
}

function pause() {
    tape.pause();
    deck.src = "images/cool-deck.png"
}

function isLastTrack(current, tracks) {
    return current + 1 === tracks.length;
}

function getTrack(time, currentTrackIndex, trackData) {
    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]) {
            currentTrackIndex = nextIndex;
        }

        return trackData[currentTrackIndex];
    }
}