summaryrefslogtreecommitdiff
path: root/docs/assets/js/audio-player.js
blob: 4dbe601c15bda34dc50bfaa8381fd41abca0af7c (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
72
73
74
75
76
document.addEventListener("DOMContentLoaded", function(){

var is_mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)
var links = document.querySelectorAll("a")
var audio, music = [], current_index = -1, typing = false
// var comment = document.querySelector("#comment")
Array.prototype.slice.apply(links).forEach(function(url){
  if (url.href.match(/\.(mp3|wav|ogg)/i)) {
    var index = music.length
    if (is_mobile) url.href = url.href.replace(/^https/,"http")
    music.push(url)
    url.addEventListener("click", function(e){
      if (e.ctrlKey || e.altKey || e.metaKey || e.shiftKey) return
      e.preventDefault()
      play(index)
    })
  }
  else if (url.href.match(/(gif|jpe?g|png|bmp)/i)) {
    url.innerHTML = "<img src='" + url.href + "'>"
    url.addEventListener("click", function(e){
      if (e.ctrlKey || e.altKey || e.metaKey || e.shiftKey) return
      e.preventDefault()
      url.classList.toggle("zoomed")
    })
  }
})
if (music.length) {
  audio = document.createElement("audio")
  audio.setAttribute("controls", true)
  audio.addEventListener("ended", next)
  audio.src = music[0]
  var player = document.querySelector("table")
  player.parentNode.insertBefore(audio, player)
  document.body.addEventListener("keydown", keydown)
  // comment.addEventListener("focus", focusTextBox)
  // comment.addEventListener("blur", blurTextBox)
}
function play(index){
  current_index = (index + music.length) % music.length
  audio.src = music[current_index].href
  audio.play()
  var playing = document.querySelector(".playing")
  if (playing) playing.classList.remove("playing")
  music[current_index].classList.add("playing")
}
function prev(){
  play(current_index - 1)
}
function next(){
  play(current_index + 1)
}
function toggle(){
  if (audio.paused) audio.play()
  else audio.pause()
}
function keydown(e){
  if (typing || e.ctrlKey || e.altKey || e.metaKey || e.shiftKey) return
  switch (e.keyCode) {
    case 37: // left
      prev()
      break;
    case 39: // right
      next()
      break;
    case 32: // spacebar
      e.preventDefault()
      toggle()
      break;
  }
}
function focusTextBox (){ typing = true }
function blurTextBox (){ typing = false }

})