我需要使用最少的代码播放多个音频文件。
在下面的代码中,每次我想播放另一种声音时,我都需要重用相同的代码。
<!-- html buttons -->
<button class="btn" id="playBtn">play</button></br>
<button class="btn" id="playBtn2">play2</button>
<!-- adding audio files using the same code twice with two variables sound and sound 2-->
<script>
var sound = new Howl({
src: ['https://www.oxfordlearnersdictionaries.com/media/english/uk_pron/f/f_1/f_1_g/f_1_gb_1_abbr.mp3']
});
playBtn.addEventListener('click', function() {
sound.play();
});
</script>
<script>
var sound2 = new Howl({
src: ['https://www.oxfordlearnersdictionaries.com/media/english/us_pron/l/lov/love_/love__us_1.mp3']
});
playBtn2.addEventListener('click', function() {
sound2.play();
});
</script>
是否可以添加更多音频文件,但使用更少的代码。 谢谢:)
答案 0 :(得分:0)
创建音乐文件的网址和声音数组:
let myUrls = ["url1", "url2", "url3"];
let sounds = new Array(myUrls.length);
遍历该数组以创建您的元素:
myUrls.forEach((url, i) => {
sounds[i] = new Howl({
src: [url]
})
let elem = document.createElement("button");
elem.class = "btn";
elem.id = `playBtn${i}`;
elem.addEventListener('click', () => sounds[i].play());
elem.innerText = `Play Sound ${i}`
// Don't forget to add them to your target node!
document.body.append(elem);
})
希望能使您走上正确的轨道。
答案 1 :(得分:0)
您可以创建所需的声音数组并动态创建按钮
<!-- html container for buttons-->
<div id="btn-container"></div>
<script>
var files = ['https://www.oxfordlearnersdictionaries.com/media/english/uk_pron/f/f_1/f_1_g/f_1_gb_1_abbr.mp3', 'https://www.oxfordlearnersdictionaries.com/media/english/us_pron/l/lov/love_/love__us_1.mp3']; // add more urls here and buttons appear dynamically
var sounds = files.map(audio => new Howl({src:[audio]}));
var html = sounds.map((sound) => {
let btn = document.createElement("button");
btn.class = "btn";
btn.addEventListener('click', () => sound.play());
document.querySelector('#btn-container').append(elem);
})