Javascript/html5 播放多个音频文件或重叠音频
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18015680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript/html5 play multiple audio files or overlap audio
提问by user2582299
Let me start by saying I am trying to play a mp3 file whenever the player collides with a wall, simple enough and done. But I wish to have another sound file play when the player hits another wall.
I have tried using both <audio>
tag in the html file, than playing it in Javascript:
首先让我说,每当播放器与墙壁发生碰撞时,我都会尝试播放 mp3 文件,这很简单并且已经完成。但是我希望在玩家撞到另一面墙时播放另一个声音文件。我尝试<audio>
在 html 文件中同时使用这两个标签,而不是在 Javascript 中播放:
var sound = document.getElementById("TheHtml5Tag");
Still the same issue, only one sound can be played, the next sound won't play untill the first one is finished. Even when using multiple <audio>
tags and multiple sounds.Next I have tried using codes similar too:
还是同样的问题,只能播放一个声音,直到第一个声音播放完毕才会播放下一个声音。即使使用多个<audio>
标签和多个声音。接下来我也尝试使用类似的代码:
sound = new Audio('Wall_Hit_01.mp3');
sound.addEventListener('ended', function() {
this.currentTime = 0;
}, false);
Than playing it with: sound.play();
But still the same issue: I can't play sound2.play();
or sound3.play();
before the first sound has finished.
Any answers/ suggestions are much appreciated. If there isn't a way to do this on every browser maybe some tips on how too stop all the sounds in order to play a new sound would be nice. Though I would much rather go with the original question.
比播放它:sound.play();
但仍然是同样的问题:我无法播放sound2.play();
或sound3.play();
在第一个声音完成之前。非常感谢任何答案/建议。如果没有办法在每个浏览器上执行此操作,那么有关如何停止所有声音以播放新声音的一些提示会很好。尽管我更愿意回答最初的问题。
回答by jsantell
回答by jsantell
I found a pretty neat solution that utilizes pure JavaScript.
我找到了一个使用纯 JavaScript 的非常简洁的解决方案。
In my HTML File, I put two audio elements and a play audio buttons in the same div.
在我的 HTML 文件中,我将两个音频元素和一个播放音频按钮放在同一个 div 中。
<div id="audioplay">
<audio id='audio1' src="ex1.wav" type="audio/wav" preload="auto" autobuffer controls ></audio>
<audio id='audio2' src="ex2.wav" type="audio/wav" preload="auto" autobuffer controls></audio>
<button id='playaudio' onclick='playAudio()'>Play Audio</input>
In my JS file (you could use a script tag too), I put this code, which plays both of the files. Make sure that your audio src tags point to the right place!
在我的 JS 文件中(你也可以使用脚本标签),我放了这段代码,它可以播放这两个文件。确保您的音频 src 标签指向正确的位置!
function playAudio(){
var audio1 = document.getElementById('audio1');
var audio2 = document.getElementById('audio2');
audio1.play();
audio2.play();
}
Hope this helps!
希望这可以帮助!