另一个启动时停止播放声音的Javascript [英] Javascript to stop playing sound when another starts
问题描述
因此,在编码方面,我是一个完全的业余爱好者,但是我仍然喜欢摆弄它.我目前正在开发基于html/jS/PHP的音板,而且我想不通如何在按下一个按钮来播放另一个声音时停止播放声音.
So, I'm a complete amateur when it comes to coding, but I still like to fiddle around with it. I'm currently working on a html/jS/PHP based soundboard and I can't figure out how to stop sound from playing when pressing a button to play another one.
<script type="text/javascript" charset="utf-8">
$(function() {
$("audio").removeAttr("controls").each(function(i, audioElement) {
var audio = $(this);
var that = this; //closure to keep reference to current audio tag
$("#doc").append($('<button>'+audio.attr("title")+'</button>').click(function() {
that.play();
}));
});
});
</script>
我希望有人能理解.提前致谢.还有一个PHP代码可以从文件夹自动提取音频文件到前端,这可能是解决此问题的不必要信息.
I hope someone understands that. Thanks in advance. There is also a PHP code to fetch the audio file automatically from the folder to the front end, probably unnecessary info for this problem.
推荐答案
如果您使用引入这是您要执行的操作的最少代码:
Here is the minimal code for what you are trying to do:
// Let's create a soundboard module ("sb")
var sb = {
song: null,
init: function () {
sb.song = new Audio();
sb.listeners();
},
listeners: function () {
$("button").click(sb.play);
},
play: function (e) {
sb.song.src = e.target.value;
sb.song.play();
}
};
$(document).ready(sb.init);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Audio</title>
</head>
<body>
<button value="https://www.gnu.org/music/FreeSWSong.ogg">Song #1</button>
<button value="https://www.gnu.org/music/free-software-song-herzog.ogg">Song #2</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
您还可以考虑使用 howler.js 之类的库来帮助您进行开发.
You may also consider libraries like howler.js to help you in the development process.
这篇关于另一个启动时停止播放声音的Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!