如何暂停所有在页面上播放的音频 [英] how to pause all playing audios on a page

查看:105
本文介绍了如何暂停所有在页面上播放的音频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html5播放器,其工作方式如下:

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:

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

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

我该怎么办

推荐答案

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

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

});






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

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

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>

这篇关于如何暂停所有在页面上播放的音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆