gpt4 book ai didi

javascript - 一次播放一个 HTML 音频元素

转载 作者:行者123 更新时间:2023-12-03 06:59:39 25 4
gpt4 key购买 nike

我有很多 audio单个页面上的元素,我想一次只播放一个元素。那就是如果一个 audio元素正在播放,我点击另一个元素的播放,前一个 audio元素应该暂停。

我从另一个问题中找到了一个 jQuery 代码来执行此操作,但它使用图像作为播放/暂停控件。我正在使用内置 controls='controls' audio 的属性元素代替。是否可以使用 jQuery 来控制 audio 的播放/暂停功能?元素在我的情况下?

这是我的 HTML 代码

<div>
<p class="song"><h3><strong>#1 Intro - The Oath</strong></h3><p>
<audio class="playback" src=http://geo-samples.beatport.com/lofi/5005876.LOFI.mp3 controls='controls' preload="none">
<I>Your browser does not support the audio element.</I>
</audio>
</div>

<div>
<p class="song"><h3><strong>#2 A State Of Trance Year Mix 2013</strong></h3></p>
<audio class="playback" src=http://geo-samples.beatport.com/lofi/5005933.LOFI.mp3 controls='controls' preload="none">
<I>Your browser does not support the audio element.</I>
</audio>
</div>

这是jQuery代码
$(document).ready(function() {
var curPlaying;

$(function() {
$(".playback").click(function(e) {
e.preventDefault();
var song = $(this).next('audio')[0];
if(song.paused){
song.play();
if(curPlaying) $("audio", "#"+curPlaying)[0].pause();
} else { song.pause(); }
curPlaying = $(this).parent()[0].id;
});
});
});

jQuery 代码似乎对我不起作用。

最佳答案

$(function(){
$("audio").on("play", function() {
$("audio").not(this).each(function(index, audio) {
audio.pause();
});
});
});

See sample at JSFiddle

关于javascript - 一次播放一个 HTML 音频元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64294539/

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