summaryrefslogtreecommitdiff
path: root/public/assets/js/lib/views/details/audio.js
blob: 42f5376255bdb216416352b50d37587ae49a468f (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
var audio = (function(){
  var audio = {}
  
  var el, music = [], current_index = -1
  var links, comment, parent
  var playing = false

  audio.init = function () {
    links = document.querySelectorAll("a")
    comment = document.querySelector("#comment")
    parent = document.querySelector("#audio")

    Array.prototype.slice.apply(links).forEach(function(url){
      if (! url.href.match(/(mp3|wav|ogg)/)) return
      url.dataset.index = music.length
      music.push(url)
    })
    audio.build()
  }
  audio.build = function () {
    el = document.createElement("audio")
    el.setAttribute("controls", true)
    el.addEventListener("loadeddata", () => { if (playing) el.play() })
    el.addEventListener("ended", audio.next)
    el.src = music[0]
    parent.appendChild(el)
    document.body.addEventListener("keydown", audio.keydown)
  }
  audio.destroy = function () {
    el.pause()
    el = null
    parent.removeChild(el)
    document.body.removeEventListener("keydown", audio.keydown)
  }
  audio.play = function (index) {
    current_index = (parseInt(index) + music.length) % music.length
    el.src = music[current_index].href
    playing = document.querySelector(".playing")
    if (playing) playing.classList.remove("playing")
    music[current_index].classList.add("playing")
  }
  audio.prev = function (){
    audio.play(current_index - 1)
  }
  audio.next = function (){
    audio.play(current_index + 1)
  }
  audio.toggle = function (){
    if (el.paused) el.play()
    else el.pause()
  }
  audio.keydown = function(e){
    if (app.typing || e.ctrlKey || e.altKey || e.metaKey || e.shiftKey) return
    switch (e.keyCode) {
      case 37: // left
        audio.prev()
        break;
      case 39: // right
        audio.next()
        break;
      case 32: // spacebar
        e.preventDefault()
        audio.toggle()
        break;
    }
  }
  
  return audio

})()