gpt4 book ai didi

javascript - 如何通过单击按钮切换音频播放()暂停()?

转载 作者:行者123 更新时间:2023-12-01 01:53:00 25 4
gpt4 key购买 nike

我已向我的网站添加了音频,该音频在打开网站时播放。现在我想添加播放/暂停按钮来切换音频。

这是我尝试的方法:

<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>

但它对我不起作用。谁能告诉我我哪里出了问题?

最佳答案

出于演示目的,我添加了 video 标签,要处理音频,您可以将 video 替换为 audio 标签并使用

$('.play-pause')

而不是

$('a.audio-btn')

对于音频,请在 video 标记的位置使用它:

<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>

$(document).ready(function () {
var playing = true;
$('.play-pause').click(function () {
if (playing == false) {
document.getElementById('myAudio').play();
playing = true;
$(this).text("Sop Sound");

} else {
document.getElementById('myAudio').pause();
playing = false;
$(this).text("Restart Sound");
}
});
});
a {
background: #000;
color: #fff;
cursor: pointer;
padding: 10px;
}
video {
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video id="myAudio" autoplay>
<source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type='video/mp4'>
Your user agent does not support the HTML5 Audio element.
</video>
<a type="button" class="play-pause" title="play/pause">Play / Pause</a>

关于javascript - 如何通过单击按钮切换音频播放()暂停()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51276757/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com