Javascript: script setup for multiple audio players and fade effect

I'm looking for a way to tweak this code so that it works with multiple players on the same page and adds a fade effect when paused / played:

var playing = false;
playpause.addEventListener('click', function () {
    if (!playing) {
        document.getElementById('player').play();
        this.src = 'pause.png';
    } else {
        document.getElementById('player').pause();
        this.src = 'play.png';
    }
    playing = !playing;
});

This unbearable fragment is what I use now to make it work with different tracks (using different identifiers) ....

var playing = false;
playpause01.addEventListener('click', function () {
    if (!playing) {
        document.getElementById('player01').play();
        this.src = 'pause.png';
    } else {
        document.getElementById('player01').pause();
        this.src = 'play.png';
    }
    playing = !playing;
});
playpause04.addEventListener('click', function () {
    if (!playing) {
        document.getElementById('player04').play();
        this.src = 'pause.png';
    } else {
        document.getElementById('player04').pause();
        this.src = 'play.png';
    }
    playing = !playing;
});
playpause13.addEventListener('click', function () {
    if (!playing) {
        document.getElementById('player13').play();
        this.src = 'pause.png';
    } else {
        document.getElementById('player13').pause();
        this.src = 'play.png';
    }
    playing = !playing;
});

Here's the "working" JSFiddle with HTML and JS: http://jsfiddle.net/multiformeingegno/jdk0b5L4/

So, how can I rewrite this to mix tracks in the same function, stop playing one track if another is selected, and add a fade effect?

+4
source share
2 answers

Well..

, jQuery - ?, .

, . , .

( true/false, "", "", "", "",)

http://jsfiddle.net/jdk0b5L4/2/

var playing = [];

images =  document.getElementsByTagName("img")
for(var i = 0; i < images.length; i++)
{
    if(images[i].hasAttribute("class") && images[i].getAttribute("class") == "playPause")
    {
        images[i].addEventListener('click', function () {
            console.info("pressed play/pause on ", this)
            var ID = this.getAttribute("id").replace("playpause", "")

            if (!playing[ID]) {
                document.getElementById('player' + ID).play();
                this.src = 'http://luca-longobardi.com/files/img/pause.png';
                playing[ID] = true;
            } else {
                document.getElementById('player' + ID).pause();
                this.src = 'http://luca-longobardi.com/files/img/play.png';
                playing[ID] = false;
            }
        });
    }

, jQuery. / HTML5

, jquery, , , - , javascript-.

: http://jsfiddle.net/jdk0b5L4/5/

+1

-, -, fade-in/out.

play this -.

-, API - CORS. , , .

- . , , / - /.

fade:

var audioElements = document.querySelectorAll("audio"), i, // get all audio elements
    audioWrappers = [];                                    // holds our wrapper object

// bind common handler for each audio element in page:
for(i = 0; i < audioElements.length; i++) {
  audioWrappers.push(new AudioFader(audioElements[i]));    // create wrapper
  audioElements[i].addEventListener("play", playHandler);  // add handler
}

// common handler for play
function playHandler() {
  // this = element triggering the even - fade-out all others but ours
  for(var i = 0, w; w = audioWrappers[i]; i++) {
    if (this !== w.audio) w.fadeOut(1500, 1);
    else w.fadeIn(1500, 1);
  }
}

// wrapper
function AudioFader(audio) {
  var isPausing = false;
  this.audio = audio;                              // expose so we can compare

  this.fadeIn = function(time, dst) {              // fade-in (time in ms, dst volume)
    isPausing = false;
    audio.play();                                  // play
    if (audio.volume === dst) return;              // hasn't been faded-out
    var startTime = Date.now();                    // start-time
    (function loop() {
      var t = (Date.now() - startTime) / time;     // normalize t [0, 1]
      audio.volume = Math.min(1, t) * dst;         // set volume, max 1
      if (!isPausing && t < dst)                   // loop if t to go and not pausing
        requestAnimationFrame(loop);
    })();
  };
  
  this.fadeOut = function(time, src) {             // fade-out (time in ms, src volume)
    isPausing = true;
    if (audio.paused) return;                      // exit if already paused
    audio.volume = src;                            // start with src volume
    var startTime = Date.now();
    (function loop() {
      var t = (Date.now() - startTime) / time;
      audio.volume = Math.max(0, 1 - t) * src;     // t is 0..1, so reverse 1-t
      if (isPausing && t < 1) requestAnimationFrame(loop);
      else {
        audio.pause();                             // eventually pause
        audio.volume = 0;                          // mute volume
      }
    })();
  };
}
<i>Preload time may vary, be patient... (due to links IE will not be able to play these)</i><br>Starting one will stop all others<br>
<audio preload="auto" controls src="https://github.com/epistemex/free-music-for-test-and-demo/blob/master/music/kf_feelme.mp3?raw=true"></audio><br>
<audio preload="auto" controls src="https://github.com/epistemex/free-music-for-test-and-demo/blob/master/music/kf_colibris.mp3?raw=true"></audio><br>
<audio preload="auto" controls src="https://github.com/epistemex/free-music-for-test-and-demo/blob/master/music/kf_limitless.mp3?raw=true"></audio><br>
<audio preload="auto" controls src="https://github.com/epistemex/free-music-for-test-and-demo/blob/master/music/kf_thebattle.mp3?raw=true"></audio>
Hide result
+4

All Articles