Javascript单击以播放音乐网址

时间:2018-10-06 09:45:41

标签: javascript html audio html5-audio audio-player

我需要一个示例代码来单击以播放音乐。我正在从系统文件夹中获取所有mp3文件,我想播放这些音乐。

我的代码是这样的

<a href="mp3folder/mp3name.mp3">mp3name</a>
<a href="mp3folder/mp3name1.mp3">mp3name1</a>
<a href="mp3folder/mp3name2.mp3">mp3name2</a>
<a href="mp3folder/mp3name3.mp3">mp3name3</a>

我应该如何使用JavaScript来解决这个问题?

2 个答案:

答案 0 :(得分:2)

您可以使用audio标记播放音频,如果要在此处播放另一个音频文件的情况下暂停一个音频,则是一个简单的javascript代码

检查当前正在播放的元素以及pause当前正在播放的音频。

MDN中了解有关audio标签的更多信息

document.addEventListener('play', function(element){
    var audios = document.getElementsByTagName('audio');

    for(var i = 0, len = audios.length; i < len; i++){

        if(audios[i] != element.target){
            audios[i].pause();
        }
    }

}, true);

document.addEventListener('play', function(element){
    var audios = document.getElementsByTagName('audio');
    
    for(var i = 0, len = audios.length; i < len; i++){
        
        if(audios[i] != element.target){
         // console.log("audio paused");
            audios[i].pause();
        }
    }
  
}, true);
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
  </head>
  <body>
    <div>
      <a href="#" onclick="document.getElementById('p1').play()">Play 1</a>
      <a href="#" onclick="document.getElementById('p2').play()">Play 2</a>
      <a href="#" onclick="document.getElementById('p3').play()">Play 3</a>
      <a href="#" onclick="document.getElementById('p4').play()">Play 4</a>
    </div>
    <audio
           id="p1"
           src="https://soundbible.com/mp3/Tyrannosaurus%20Rex%20Roar-SoundBible.com-807702404.mp3">
      Your browser does not support the <code>audio</code> element.
    </audio>
    <audio
           id="p2"
           
           src="https://soundbible.com/mp3/Tyrannosaurus%20Rex%20Roar-SoundBible.com-807702404.mp3">
      Your browser does not support the <code>audio</code> element.
    </audio>
    <audio
           id="p3"
           
           src="https://soundbible.com/mp3/Tyrannosaurus%20Rex%20Roar-SoundBible.com-807702404.mp3">
      Your browser does not support the <code>audio</code> element.
    </audio>
    <audio
           id="p4"
           
           src="https://soundbible.com/mp3/Tyrannosaurus%20Rex%20Roar-SoundBible.com-807702404.mp3">
      Your browser does not support the <code>audio</code> element.
    </audio>
    <audio
           id="p5"
           
           src="https://soundbible.com/mp3/Tyrannosaurus%20Rex%20Roar-SoundBible.com-807702404.mp3">
      Your browser does not support the <code>audio</code> element.
    </audio>

  

  </body>
</html>

来源:multiple audio html : auto stop other when current is playing with javascript

答案 1 :(得分:0)

您可以使用embed标签播放音频文件

html

<embed src="mp3folder/mp3name.mp3" autostart="false" id="mp3name" enablejavascript="yes">

javascript

var mp3name = document.getElementById("mp3name");
mp3name.play();