HTML5音频标签 - 更改源不自动播放

时间:2016-02-14 14:39:26

标签: html5 audio

我试图更改当前播放的音频源。但它没有播放这首歌。调用audio.load()后,将为资源发送GET请求,结果为HTTP 200 OK。我在调用audio.play()之前尝试设置间隔2秒,但这也没有解决我的问题。控制台没有给出任何错误消息。

<audio id="audioPlayer" controls="controls" autoplay>
    <source id="audioSource" src="audio/myFirstSong.mp3" type="audio/mpeg" />
</audio>



function updateSource(songName) {
    songName = "audio/" + escape(songName) + ".mp3";
    var audio = document.getElementById('audioPlayer');

    var source = document.getElementById('audioSource');
    source.src = songName;

    audio.load();//GET 200 OK
    audio.play(); //Doesn't play
    //Can't press the Play button in the controls either
}

1 个答案:

答案 0 :(得分:1)

我没有改变原始代码的大部分内容:

  • controls="controls"controls

  • 音频源已更改

  • 添加了一个按钮和一个事件监听器来调用updateSource()函数。

我真的不明白为什么我的演示与你的演示有很大不同-_-

http://plnkr.co/edit/GjYRjVqdRdCYSIUWuYoL?p=preview

<!DOCTYPE html>
<html>

<head>

</head>

<body>
  <audio id="audioPlayer" controls autoplay>
    <source id="audioSource" src="https://glpjt.s3.amazonaws.com/so/av/fightclub.mp3" type="audio/mpeg" />
  </audio>
  <button id="btn1">Update</button>

  <script>
    function updateSource(songName) {
      songName = "https://glpjt.s3.amazonaws.com/so/av/" + escape(songName) + ".mp3";
      var audio = document.getElementById('audioPlayer');

      var source = document.getElementById('audioSource');
      source.src = songName;

      audio.load(); //GET 200 OK
      audio.play(); //Doesn't play
      //Can't press the Play button in the controls either
    }

    var btn1 = document.getElementById('btn1');
    btn1.addEventListener('click', function(e) {
      var songName = "pf-righteous";
      updateSource(songName);
    }, false);
  </script>
</body>

</html>