gpt4 book ai didi

javascript - jQuery:多个音频播放器按钮

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

我想制作 4 个播放 mp3 音频的播放按钮。播放功能每 4 个按钮都起作用,但不幸的是,暂停功能对它们中的任何一个都不起作用。也许暂停条件是错误的?

<div class="audio-button">
<audio src="media/test.mp3"></audio>
</div>
<div class="audio-button">
<audio src="media/test2.mp3"></audio>
</div>
<div class="audio-button">
<audio src="media/test3.mp3"></audio>
</div>
<div class="audio-button">
<audio src="media/test4.mp3"></audio>
</div>
$(document).ready(function() {
var playing = false;

$('.audio-button').click(function() {
$(this).toggleClass("playing");
var song = $(this).find('audio').attr('src');
var audio = new Audio(song);

if (playing == false) {
audio.play();
playing = true;
} else {
audio.pause();
playing = false;
}
});
});

最佳答案

您需要直接从按钮中获取音频元素作为子元素并与之交互。您不需要使用构造函数克隆 Audio 对象。

$(document).ready(function() {
var playing = false;

// Add file names.
$('.audio-button').each(function() {
var $button = $(this);
var $audio = $button.find('audio');

$($('<span>').text($audio.attr('src'))).insertBefore($audio);
});

// Add click listener.
$('.audio-button').click(function() {
var $button = $(this);
var audio = $button.find('audio')[0]; // <-- Interact with this!

// Toggle play/pause
if (playing !== true) {
audio.play();
} else {
audio.pause();
}

// Flip state
$button.toggleClass('playing');
playing = !playing
});
});
.fa.audio-button {
position: relative;
display: block;
width: 12em;
height: 2.25em;
margin-bottom: 0.125em;
text-align: left;
}

.fa.audio-button:after {
position: absolute;
right: 0.8em;
content: "\f04b";
}

.fa.audio-button.playing:after {
content: "\f04c";
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="fa audio-button">
<audio src="media/test.mp3"></audio>
</button>
<button class="fa audio-button">
<audio src="media/test2.mp3"></audio>
</button>
<button class="fa audio-button">
<audio src="media/test3.mp3"></audio>
</button>
<button class="fa audio-button">
<audio src="media/test4.mp3"></audio>
</button>

关于javascript - jQuery:多个音频播放器按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37836002/

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