]> iEval git - app-musicexpo.git/blame - player.js
Click song titles to play certain songs
[app-musicexpo.git] / player.js
CommitLineData
9b989f96
MG
1'use strict';
2var TYPES = {
3 "FLAC": "audio/x-flac",
4 "Vorbis": "audio/ogg",
5 "AAC": "audio/aac",
6 "MP3": "audio/mpeg"
7};
8
9var audio, details, start, data;
10
11function load_song (id) {
12 audio.style.display = "inline";
2e6185c6 13 var song = data[id];
9b989f96
MG
14 var old_sources = document.getElementsByTagName("source");
15 while(old_sources.length)
16 old_sources[0].parentNode.removeChild(old_sources[0]);
17
18 for (var i = 0 ; i < song.formats.length ; i++){
19 var source = document.createElement("source");
20 var type = TYPES[song.formats[i].format];
21 source.setAttribute("type", type);
2e6185c6 22 source.setAttribute("src", song.formats[i].file);
9b989f96
MG
23 audio.appendChild(source);
24 }
25
26 details.innerHTML = "Now playing: " + song.artist + " - " + song.title;
27 audio.load();
28}
29
30function play_random () {
31 start.innerHTML = "Next";
2e6185c6 32 var id = Math.floor(Math.random() * data.length);
9b989f96
MG
33 load_song(id);
34 audio.play();
35}
36
2e6185c6
MG
37function make_onclick_handler (id){
38 return function () {
39 load_song(id);
40 start.innerHTML = "Next";
41 audio.play();
42 }
43}
44
9b989f96
MG
45window.onload = function () {
46 var container = document.getElementById("player");
2e6185c6 47 container.innerHTML = '<div id="details"></div> <button id="start_player">Play a random song</button> (or click a song title)<br><audio id="audio" controls></audio>';
9b989f96
MG
48 audio = document.getElementById("audio");
49 details = document.getElementById("details");
50 start = document.getElementById("start_player");
51
2e6185c6
MG
52 data = [];
53 var trs = document.querySelectorAll("tbody tr");
54 for (var i = 0 ; i < trs.length ; i++) {
55 var tr = trs[i];
56 var song = {
57 "artist": tr.getElementsByClassName("artist")[0].textContent,
58 "title": tr.getElementsByClassName("title")[0].textContent,
59 "formats": []
60 };
61 var formats = tr.getElementsByClassName("formats")[0].getElementsByTagName("a");
62 for (var j = 0 ; j < formats.length ; j++) {
63 var format = formats[j];
64 song.formats.push({
65 "format": format.textContent,
66 "file": format.getAttribute("href")
67 });
68 }
69 data.push(song);
70 tr.getElementsByClassName("title")[0].onclick = make_onclick_handler(i);
71 }
9b989f96
MG
72
73 audio.style.display = "none";
74 audio.addEventListener('ended', play_random);
e500af14 75 audio.addEventListener('error', play_random);
9b989f96
MG
76 start.addEventListener('click', play_random);
77};
This page took 0.028425 seconds and 4 git commands to generate.