强制JS中的音频库加载

时间:2016-11-11 23:29:08

标签: javascript javascript-audio-api

我想获得音频长度而不必播放然后暂停然后再次播放以获得音频长度/持续时间?

调用的函数将是:this.createRangeElement

但由于某种原因它会输出“NaN”,那么我如何强制音频渲染?

function get_uai(){ return new uai(); }
function uai(){
  var AE = new Audio();
  var played = false;

  this.src = "";
  this.set_src = function(){ AE.src = this.src; AE.load(); }


  this.play = function(){
    if(played == true){
      AE.play();
    }else{
      AE.src = this.src;
      played = true;
      AE.play();
    }
  };

  this.pause = function(){
    AE.pause();
  }

  this.stop = function(){
    window.aui = undefined;
  }


  this.createRangeElement = function(){
    var min = "0";
    AE.load();
    var max = AE.duration;
    console.log(max);
  }

}


// Getting the UAI API
      var aud = get_uai();

      // Setting the source
      aud.src = "http://crossorigin.me/https://s3-us-west-2.amazonaws.com/s.cdpn.io/1715/the_xx_-_intro.mp3";
      aud.set_src();

      // Creating a range element
      aud.createRangeElement();

      // Playing the sound
      //aud.play()
<html>
  <head>
    <title>Music Player</title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
  </head>
  <body>
    <em class="fa fa-pause" onclick="aud.pause();"></em>
    <em class="fa fa-play" onclick="aud.play();"></em>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

您可以使用oncanplaythrough事件来检测音频持续时间数据是否可用。

&#13;
&#13;
function get_uai() {
    return new uai();
}

function uai() {
    var AE = new Audio();
    var played = false;

    this.src = "";
    this.set_src = function() {
        AE.src = this.src;
        AE.load();
    }

    this.play = function() {
        if (played == true) {
            AE.play();
        } else {
            AE.src = this.src;
            played = true;
            AE.play();
        }
    };

    this.pause = function() {
        AE.pause();
    }

    this.stop = function() {
        window.aui = undefined;
    }


    this.createRangeElement = function() {
        var min = "0";
        AE.load();
        AE.oncanplaythrough = function() {
            var max = AE.duration;
            console.log(max);
        }
    }

}

var aud = get_uai();
aud.src = "http://crossorigin.me/https://s3-us-west-2.amazonaws.com/s.cdpn.io/1715/the_xx_-_intro.mp3";
aud.set_src();
aud.createRangeElement();
&#13;
<html>
  <head>
    <title>Music Player</title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
  </head>
  <body>
    <em class="fa fa-pause" onclick="aud.pause();"></em>
    <em class="fa fa-play" onclick="aud.play();"></em>
  </body>
</html>
&#13;
&#13;
&#13;