aboutsummaryrefslogtreecommitdiff
path: root/static/music_player.js
blob: 63fa46c74da4e388296d237c1565cb59347c625f (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
61
62
63
64
65
66
67
68
69
70
71
let audio = document.createElement("audio");
let tick;

async function mpFetchAsync (url) {
    let response = await fetch(url);
    let data = await response.json();

    return data;
}

function mpFormatTime (number) {
    let min = Math.floor(number / 60);
    let sec = Math.floor(number - min * 60);

    if (min < 10) { min = "0" + min; }
    if (sec < 10) { sec = "0" + sec; }

    return min + ":" + sec;
}

function mpTick () {
    let seek = document.getElementById("mp_seek_slider");
    let current = document.getElementById("mp_current_time");
    let duration = document.getElementById("mp_total_duration");

    let seekPos = 0;

    if (!isNaN(audio.duration)) {
        seekPos = audio.currentTime * (100 / audio.duration);
        seek.value = seekPos;

        current.textContent = mpFormatTime(audio.currentTime);
        duration.textContent = mpFormatTime(audio.duration); // This shouldn't be necessary but initial update doesn't always work???
    }
}

async function mpUpdate () {
    clearInterval(tick);

    const trackSelector = document.getElementById("mp_tracks");
    const trackName = trackSelector.value;

    let duration = document.getElementById("mp_total_duration");
    duration.textContent = mpFormatTime(audio.duration);

    audio.src = "/audio/get?file=" + trackName;
    audio.currentTime = 0;

    tick = setInterval(mpTick, 1000);
}

function mpIsPlaying() {
    return !audio.paused;
}

function mpPpTrack() {
    mpIsPlaying() ? audio.pause() : audio.play();
}

const trackList = await mpFetchAsync("/audio");
let trackSelector = document.getElementById("mp_tracks");

trackList.forEach((track) => {
    let option = document.createElement("option");
    option.text = track;

    trackSelector.add(option, 0);
});

document.getElementById("mp_tracks").addEventListener("change", mpUpdate, false);
document.getElementById("mp_pp_track").addEventListener("click", mpPpTrack, false);