当我点击按钮时,我正在尝试播放一个音频文件,但是它不工作,我的html代码是:
<html>
<body>
<div id="container">
<button id="play">
Play Music
</button>
</div>
</body>
</html>
我的JavaScript是:
$('document').ready(function () {
$('#play').click(function () {
var audio = {};
audio["walk"] = new Audio();
audio["walk"].src = "http://www.rangde.org/static/bell-ring-01.mp3"
audio["walk"].addEventListener('load', function () {
audio["walk"].play();
});
});
});
我也为此创建了一个Fiddle。
发布于 2013-01-29 04:23:26
对于其他跟进的人,我简单地接受了Ahmet的答案,并更新了原始发问者的jsfiddle here,替换为:
audio.mp3
为
http://www.uscis.gov/files/nativedocuments/Track%2093.mp3
在网络上免费提供的mp3链接。感谢您分享这个简单的解决方案!
发布于 2014-07-09 22:45:41
我这里有一个很好的通用的解决方案,有一个后备:
<script type="text/javascript">
var audiotypes={
"mp3": "audio/mpeg",
"mp4": "audio/mp4",
"ogg": "audio/ogg",
"wav": "audio/wav"
}
function ss_soundbits(sound){
var audio_element = document.createElement('audio')
if (audio_element.canPlayType){
for (var i=0; i<arguments.length; i++){
var source_element = document.createElement('source')
source_element.setAttribute('src', arguments[i])
if (arguments[i].match(/\.(\w+)$/i))
source_element.setAttribute('type', audiotypes[RegExp.$1])
audio_element.appendChild(source_element)
}
audio_element.load()
audio_element.playclip=function(){
audio_element.pause()
audio_element.currentTime=0
audio_element.play()
}
return audio_element
}
}
</script>
在此之后,您可以初始化任意数量的音频:
<script type="text/javascript" >
var clicksound = ss_soundbits('your/path/to/click.ogg', "your/path/to/click.mp3");
var plopsound = ss_soundbits('your/path/to/plopp.ogg', "your/path/to/plopp.mp3");
</script>
现在,您可以使用简单的事件调用来访问初始化的音频元素,如
onclick="clicksound.playclip()"
onmouseover="plopsound.playclip()"
发布于 2020-03-01 03:06:30
下面是什么:
$('#play').click(function() {
const audio = new Audio("https://freesound.org/data/previews/501/501690_1661766-lq.mp3");
audio.play();
});
https://stackoverflow.com/questions/8489710
复制相似问题