我尝试建立一个按钮,一旦点击它播放一个音频文件,如果再次点击它停止它。在按钮中,有一个属性src,其中放置了应该播放的文件的路径。
null
$(document).ready(function(){
$("button").click(function(){
var audio = $(this).attr('src');
alert (audio)
if (audio.paused) {
audio.play();
$(this).html("Stop me!");
} else {
audio.pause();
$(this).html("Play me!");
}
});
});
button {
background-color: #DD0050;
border:4px solid #DD0050;
color:#fff
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="234" type="button" src="http://www.soundjay.com/misc/sounds/bell-ringing-01.mp3">Play Me!</button>
null
当我尝试单击该按钮时,日志显示“uncattle typeerror:audio.pause is not a function
”。但音频已设置,警报显示文件路径在那里。
我做错了什么?
代码中的audio
变量是一个字符串。不能对字符串调用jQuery/jsaudio
方法。您需要定义一个audio
元素,在该元素上放置src
而不是按钮
,然后在该元素上调用play()
和pause()
方法。试试看:
null
jQuery($ => {
$("button").click(function() {
let $button = $(this);
let audio = $('audio')[0];
console.log(audio.src);
if (audio.paused) {
audio.play();
$button.html("Stop me!");
} else {
audio.pause();
$button.html("Play me!");
}
});
});
button {
background-color: #DD0050;
border: 4px solid #DD0050;
color: #fff
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="234" type="button">Play Me!</button><br />
<audio src="http://www.soundjay.com/misc/sounds/bell-ringing-01.mp3"></audio>