多个音频地址捕捉到项目HTML

时间:2019-01-31 06:30:33

标签: javascript jquery dom

需要帮助的Web开发人员。 如何在函数jquery中注册多个音频地址(url)并将mp3文件的这些地址绑定到html上的元素

<h2>W</h2>
<button id="play">Play</button>
<button id="pause">Pause</button>
<br>
<h2>E</h2>
<button id="play">Play</button>
<button id="pause">Pause</button>


$(document).ready(function() {
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 
'https://s3.amazonaws.com/freecodecamp/drums/Kick_n_Hat.mp3'); 

1 个答案:

答案 0 :(得分:0)

var addresses = ["http://www.sousound.com/music/healing/healing_01.mp3", "https://s3.amazonaws.com/freecodecamp/drums/Kick_n_Hat.mp3" ];
var body = document.getElementById("audios");
let audiohtml = [];
addresses.map((address, i)=> {
  audiohtml.push(`<audio id='myAudio${i}' src=${address} preload='auto'></audio>
<br><h2>E</h2>
<button onClick=togglePlay(${i})>Play</button>
<button onClick=togglePause(${i})>Pause</button>`)
});
body.innerHTML= audiohtml;
function togglePlay(i) {
    var myAudio = document.getElementById(`myAudio${i}`);
    myAudio.play();
};
function togglePause(i) {
    var myAudio = document.getElementById(`myAudio${i}`);
    myAudio.pause()
};
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body id='audios'>

</body>
</html>

了解更多详细信息:https://jsbin.com/sejuzoz/edit?html,js,output