如何暂停所有在页面上播放的音频

时间:2015-07-31 13:28:49

标签: javascript jquery audio html5-audio

我有一个像这样工作的html5播放器:

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 ... 

意味着所有音频播放器都是用javascript制作的,页面上没有实际的<audio>标签,我想要做的是,我需要编写一个函数,当有人点击播放按钮时音频播放器,所有其他音频播放器应暂停,我已尝试此代码,但它不起作用我认为这是因为没有实际的<audio>标签

/* 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();

我该怎么办

1 个答案:

答案 0 :(得分:4)

一种简单的方法,但可能不太理想,因为它使用全局变量,就是拥有一个包含所有音频的数组变量:

var audios = new Array();

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

    ...

    audios.push(audio);

    ...

现在,当您点击播放按钮时,您可以遍历音频数组,暂停所有这些音频但您点击的音频:

// 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;
        }
    }

});

在JSFiddle中发布代码之后,我将我的解决方案添加到您的JSFiddle中,它运行正常。你可以在这里看到它:http://jsfiddle.net/mec12jz7/16/

我在这里复制了代码(我的更改标有注释:// AM Change):

&#13;
&#13;
/**
 * 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');
    }
  });
});
&#13;
.body {
  direction:ltr !important;
  text-align:left;
}

.col {
  float:left !important;
}

.player {
  float:left !important;
}
&#13;
<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>
&#13;
&#13;
&#13;