Javascript 如何通过单击按钮切换音频播放()暂停()?
我已经添加了一个音频到我的网站,这是播放时,网站被打开。现在我想添加播放/暂停按钮来切换音频 我就是这样尝试的:Javascript 如何通过单击按钮切换音频播放()暂停()?,javascript,jquery,html5-audio,Javascript,Jquery,Html5 Audio,我已经添加了一个音频到我的网站,这是播放时,网站被打开。现在我想添加播放/暂停按钮来切换音频 我就是这样尝试的: <audio id="myAudio" autoplay > <source src="mp3/background-music.mp4" type='audio/mp4'> Your user agent does not support the HTML5 Audio element. </audio> <a type="butto
<audio id="myAudio" autoplay >
<source src="mp3/background-music.mp4" type='audio/mp4'>
Your user agent does not support the HTML5 Audio element.
</audio>
<a type="button" class="play-pause" title="play/pause"><i class="fa fa-pause"></i></a>
<script type="text/javascript">
$(document).ready(function() {
var playing = false;
$('a.audio-btn').click(function() {
if (playing == false) {
document.getElementById('myAudio').play();
playing = true;
$(this).text("stop sound");
} else {
document.getElementById('myAudio').pause();
playing = false;
$(this).text("restart sound");
}
});
});
</script>
您的用户代理不支持HTML5音频元素。
$(文档).ready(函数(){
var=false;
$('a.audio-btn')。单击(函数(){
如果(播放==错误){
document.getElementById('myAudio').play();
玩=真;
$(此).text(“停止声音”);
}否则{
document.getElementById('myAudio').pause();
玩=假;
$(此).text(“重新启动声音”);
}
});
});
但这对我不起作用。谁能告诉我哪里出了问题 到底是什么不起作用?按钮是否不出现,是否不起作用 我建议使用以下类似的方法:
var myAudio = document.getElementById("myAudio");
var isPlaying = false;
function togglePlay() {
if (isPlaying) {
myAudio.pause()
} else {
myAudio.play();
}
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
将您的
$('a.audio-btn')
更改为$('a.play-pause')
出于演示目的,我添加了video
标签,要处理音频,您可以将video
替换为audio
标签并使用
$('.play-pause')
而不是
$('a.audio-btn')
对于音频,请在视频
标签处使用此标签:
<audio id="myAudio" autoplay>
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type='audio/mp4'>
Your user agent does not support the HTML5 Audio element.
</audio>
a{
背景:#000;
颜色:#fff;
光标:指针;
填充:10px;
}
录像带{
宽度:200px;
}
您的用户代理不支持HTML5音频元素。
播放/暂停