gpt4 book ai didi

javascript - 播放/暂停所有音频链接的常规功能

转载 作者:行者123 更新时间:2023-12-03 02:30:13 31 4
gpt4 key购买 nike

我有一个带有一堆音频链接的html。我正在尝试使所有音频链接都在单击时播放/暂停,并且尝试了here解决方案。这正是我所追求的,只是我现在不得不修改此功能以应用于代码中的所有音频链接(因为我不能为每个链接定义一个功能)。有关如何执行此操作的想法?

例:

<script type="text/javascript">
function loadAudio(source) {
currentSource = source;
audioSource.src = source;
audio.load();
}

var audio = document.getElementById('audio');
var audioSource = document.getElementById('audioSource');
var currentSource;

document.querySelectorAll('.play-audio').forEach(function(link) {
link.addEventListener('click', function() {
var linkSource = this.dataset.audio;

if (currentSource === linkSource) {
if (audio.paused) {
audio.play();
} else {
audio.pause();
}
} else {
loadAudio(linkSource);
audio.play();
}
});
});
</script>

<audio id="audio">
<source id="audioSource" src=""></source>
Your browser does not support the audio format.
</audio>

<table>
<tr>
<td><a href="#" class="play-audio" data-audio="https://...1">Play 1</a></td>
</tr>
<tr>
<td><a href="#" class="play-audio" data-audio="https://...2">Play 2</a></td>
</tr>
</table>

最佳答案

如果您想一次播放一个音频。您可以根据单击的链接来更改源,从而通过相同的音频元素全部播放它们:

function loadAudio(source) {
currentSource = source;
audioSource.src = source;
audio.load();
}

var audio = document.getElementById('audio');
var audioSource = document.getElementById('audioSource');
var currentSource;

document.querySelectorAll('.play-audio').forEach(function(link) {
link.addEventListener('click', function() {
var linkSource = this.dataset.audio;

if (currentSource === linkSource) {
if (audio.paused) {
audio.play();
} else {
audio.pause();
}
} else {
loadAudio(linkSource);
audio.play();
}
});
});
<audio id="audio">
<source id="audioSource" src=""></source>
Your browser does not support the audio format.
</audio>

<a href="#" class="play-audio" data-audio="sound1.mp3">Click here to hear 1.</a>
<a href="#" class="play-audio" data-audio="sound2.mp3">Click here to hear 2.</a>
<a href="#" class="play-audio" data-audio="sound3.mp3">Click here to hear 3.</a>

关于javascript - 播放/暂停所有音频链接的常规功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56476861/

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