如何使用jQuery播放音频文件? [英] How do I play an audio file with jQuery?
本文介绍了如何使用jQuery播放音频文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很难获取音频以使用jQuery.我已经尝试过使用.wav和.ogg格式. (Firefox 19.0.2)
I'm having a difficult time getting audio to work with jQuery. I've tried this with both .wav and .ogg formats. (Firefox 19.0.2)
点击开始按钮将产生:
TypeError:buzzer.play不是函数
TypeError: buzzer.play is not a function
我不确定jQuery选择器是否返回数组,但是我尝试同时捕获两者:
I'm not sure if jQuery selectors return an array, but I've tried the capture the audio file with both:
var buzzer = $('buzzer');
和
var buzzer = $('buzzer')[0];
无论如何,我都无法播放音频元素.
Regardless, I can't get the audio elements to play.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
</head>
<body>
<audio id="buzzer" src="buzzer.ogg" type="audio/ogg">Your browser does not support the <audio> element.</audio>
<form id='sample' action="#" data-ajax="false">
<fieldset>
<input value="Start" type="submit">
</fieldset>
</form>
<script type="text/javascript">
var buzzer = $('buzzer')[0];
$(document).on('submit', '#sample', function() {
buzzer.play();
return false;
});
</script>
</body>
</html>
推荐答案
您忘记了ID选择器中的哈希#
:
You forgot the hash #
in your ID selector :
var buzzer = $('#buzzer')[0];
$(document).on('submit', '#sample', function() {
buzzer.play();
return false;
});
document.getElementById('buzzer')
似乎更合适!
我将HTML更改为:
<audio id="buzzer" src="buzzer.ogg" type="audio/ogg"></audio>
<input type="button" value="Start" id="start" />
然后做:
$('#start').on('click', function() {
$('#buzzer').get(0).play();
});
这篇关于如何使用jQuery播放音频文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文