3

I've got a html5 player which works like this :

Html :

<div class="player row" data-dwplayer="true" data-mp3="example.mp3" data-loop="true">

Javascript :

$("[data-dwplayer=true]").each(function(){
    var player = $(this);
    var audio = new Audio();

    /* data */
    var source = player.data('mp3') ? player.data('mp3') : player.data('ogg');
    var auto   = player.data('autoplay') ? true : false;
    var loop   = player.data('loop') ? true : false;

    /* set source */
    audio.src = source;

and the rest of code ... 

meaning all audio players are made with javascript and there is no actual <audio> tag on the page , what i want to do is , I need to write a function which , when some one clicks the play button for an audio player, All other audio players should pause , I've tried this code but it ain't working i think it's because there is no actual <audio> tag

/* stop other audio players */
$("audio").not(audio).each(function() {
    if( this.readyState != 0 ) {
        this.pause();
        this.currentTime = 0;
    }
});

/* play current audio player */
if( audio.paused && audio.readyState != 0 )
    audio.play();

What should i do

Amin
  • 1,637
  • 1
  • 22
  • 40
  • You are correct, `$("audio")` shouldn't do anything because there's no actual `audio` tag in the document (unless you appended it in the "and the rest of the code ..." part of the first code snippet). How do you keep track of the different audios? where do you get the `audio` variable in the last code snippet? – Alvaro Montoro Jul 31 '15 at 13:46
  • from here in the code above :`var audio = new Audio();` , i mean every thing happens in `$("[data-dwplayer=true]").each(function(){..` – Amin Jul 31 '15 at 13:48
  • Can you create a jsfiddle of what you have so far? I would like to see what is/isn't functioning. Thank you. – NewToJS Jul 31 '15 at 13:50
  • http://jsfiddle.net/mec12jz7/14/ here you go , click those tiny white play buttons – Amin Jul 31 '15 at 14:10

1 Answers1

4

An easy way, but probably not ideal as it uses global variables, would be to have an array variable that holds all the audios in it:

var audios = new Array();

$("[data-dwplayer=true]").each(function(){
    var player = $(this);
    var audio = new Audio();

    ...

    audios.push(audio);

    ...

Now when you do click on the play button, you can traverse the array of audios pausing all of them but the one you've clicked:

// check all the audios
$.each(audios, function(idx, obj) {

    // if it's the audio from the play button
    if (obj == audio) {

        // your code here to play

    // it it's a different audio
    } else {

        // your code here (using obj instead of this) to pause the other audios
        if( obj.readyState != 0 ) {
            obj.pause();
            obj.currentTime = 0;
        }
    }

});

After you posted your code in a JSFiddle, I added my solution into your JSFiddle and it works fine. You can see it here: http://jsfiddle.net/mec12jz7/16/

I copied the code here (my changes are marked with the comment: // AM Change):

/**
 * Html 5 Audio Player
 * Simple audio player for LearnFiles by iVahid.com
 *
 * @author Am!n - <info@ivahid.com>
 * @package Wordpress
 * @subpackage Learnfiles Wordpress Theme
 * @version 2.0
*/

// AM Change
var audios = new Array();

$("[data-dwplayer=true]").each(function(){
  var player = $(this);
  var audio = new Audio();
  audio.preload = 'metadata';

  /* data */
  var source = player.data('mp3') ? player.data('mp3') : player.data('ogg');
  var auto   = player.data('autoplay') ? true : false;
  var loop   = player.data('loop') ? true : false;

  /* time progress */
  var time_progress = player.find(".time-total");

  /* buttons */
  var volumeButton = player.find(".volume");
  var pauseButton  = player.find(".pause");
  var playButton   = player.find(".play");
  var playToggle   = true;

  /* set source */
  audio.src = source;

  // AM Change
  audios.push(audio);

  /**
  * Format Seconds into DD:HH:MM:SS
 */
  function formatSeconds( s ) {
    var fm = [
      Math.floor(s / 60 / 60 / 24), // DAYS
      Math.floor(s / 60 / 60) % 24, // HOURS
      Math.floor(s / 60) % 60, // MINUTES
      Math.floor(s % 60) // SECONDS
    ];
    fm = $.map(fm, function(v, i) { return ((v < 10) ? '0' : '') + v; });

    return fm;
  }

  /* format into MM:SS */
  function formatAudioTime( s ) {
    var time = formatSeconds( s );
    return time[2]+":"+time[3];
  }

  /* main stuff */
  audio.addEventListener("canplaythrough", function () {
    /* autoplay */
    if( auto ) {
      audio.play();
      playButton.removeClass("play").addClass("pause");
    }

    /**
   * Volume Handle
  */
    volumeButton.click(function() {
      if( $(this).hasClass("volume-3") ) {
        audio.muted = true;
        $(this).removeClass("volume-3")
        $(this).addClass("volume-0")
      }

      else if( $(this).hasClass("volume-0") ) {
        audio.muted = false;
        audio.volume = 0.33;
        $(this).removeClass("volume-0")
        $(this).addClass("volume-1")
      }

      else if( $(this).hasClass("volume-1") ) {
        audio.muted = false;
        audio.volume = 0.66;
        $(this).removeClass("volume-1")
        $(this).addClass("volume-2")
      }

      else if( $(this).hasClass("volume-2") ) {
        audio.muted = false;
        audio.volume = 1;
        $(this).removeClass("volume-2")
        $(this).addClass("volume-3")
      }
    });
  }, false);

  /**
  * Show audio duration if it's a playable audio.
 */
  $(audio).on("canplay",function() {
    //if( !isNaN( this.duration ) && this.duration > 0 )
    // player.find(".time-total").html( formatAudioTime( this.duration ) );
  });

  /**
  * Update passed time and progress bar while audio is being played
 */
  $(audio).on("timeupdate",function() {
    var current = this.currentTime;
    var total = this.duration;
    var bar_width = ( current / total ) * 100;

    player.find(".player-progressbar .bar").css("cursor","pointer");
    player.find(".time-passed").html( formatAudioTime( current ) );
    player.find(".player-progressbar .bar .fluid").css("width",bar_width+"%");
  });

  /**
  * Update play time position via progressbar
 */
  player.find(".player-progressbar .bar").click(function(e) {
    if( !audio.paused ) {
      var offset = $(this).offset();
      var pr_width = e.pageX - offset.left;
      var bar_width = $(this).outerWidth();
      var escaled_time = ( audio.duration * pr_width ) / bar_width;

      audio.currentTime = escaled_time;
    }
  });

  /**
  * Pause Handler
 */
  pauseButton.click(function() {
    audio.pause();
  });

  /**
  * Play Handler
 */
  playButton.click(function() {
    /* pause any other audio playing on the current page */  
    // AM Change
    $.each(audios, function(idx, obj) {
      if(obj != audio) {
        // change the play/pause icon using the nth-of-type selector
        $(".player:nth-of-type(" +(idx+1)+ ")").find(".play-pause").removeClass("pause");
        obj.pause();
        obj.currentTime = 0;
      }
    });

    /* play/pause */
    if( audio.paused && audio.readyState != 0 ) {
      audio.play();
      $(this).removeClass("play").addClass("pause");
    } else {
      /* pause */
      if( playToggle && !audio.paused ) {
        audio.pause();
        $(this).removeClass("pause").addClass("play");
      }
    }
  });

  /**
  * Finished
 */
  $(audio).on("ended",function() {
    audio.currentTime = 0;
    playButton.removeClass("pause");

    if( loop ) {
      audio.play();
      playButton.removeClass("play").addClass('pause');
    }
  });
});
.body {
  direction:ltr !important;
  text-align:left;
}

.col {
  float:left !important;
}

.player {
  float:left !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link type="text/css" href="http://learnfiles.com/wp-content/themes/learnfile/include/css/style.css" rel="stylesheet" />
<div class="player row" data-dwplayer="true" data-mp3="http://dornaweb.ir/love-club.mp3" data-loop="true">
  <div class="player-elements row">
    <span class="col time ltr">
      <strong class="time-passed">00:00</strong> / 
      <span class="time-total">03:23</span>
    </span>

    <span class="volume volume-3 volume-icon col"></span>

    <div class="player-progressbar col ltr">
      <span class="bar row"><em class="fluid go-left" style="width:0%;"></em></span>
    </div>
    <!-- .player-progressbar -->

    <span class="play play-pause col"></span>
  </div>
  <!-- .player-elements -->
</div>

<div class="player row" data-dwplayer="true" data-mp3="http://dornaweb.ir/love-club.mp3" data-loop="true">
  <div class="player-elements row">
    <span class="col time ltr">
      <strong class="time-passed">00:00</strong> / 
      <span class="time-total">03:23</span>
    </span>

    <span class="volume volume-3 volume-icon col"></span>

    <div class="player-progressbar col ltr">
      <span class="bar row"><em class="fluid go-left" style="width:0%;"></em></span>
    </div>
    <!-- .player-progressbar -->

    <span class="play play-pause col"></span>
  </div>
  <!-- .player-elements -->
</div>
Alvaro Montoro
  • 28,081
  • 7
  • 57
  • 86
  • 1
    sadly it's not working :( , here is a fiddle : http://jsfiddle.net/mec12jz7/15/ , check `line 136` javascript – Amin Jul 31 '15 at 14:23
  • 1
    I'm sorry can i ask you another question , i know it's not the place but i would appreciate your help , I wanna print the the duration of an audio but when i use `audio.duration` or `audio.currentTime` it returns `NaN` , it actually works for some audios but usually it returns `NaN` , here is the console error : `Value being assigned to HTMLMediaElement.currentTime is not a finite floating-point value.` – Amin Jul 31 '15 at 14:33
  • What is the JSFiddle? – Alvaro Montoro Jul 31 '15 at 14:37
  • http://jsfiddle.net/mec12jz7/17/ , it says : 00:00 / NaN:NaN in the time section – Amin Jul 31 '15 at 14:40
  • I see 00:00 / 03:23 in the time section – Alvaro Montoro Jul 31 '15 at 14:42
  • it's weird , i think the problem is with my browser , thank you any way alvaro <3 – Amin Jul 31 '15 at 14:45