gpt4 book ai didi

javascript - 简约的 play() 和pause() 音频解决方案

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

我在另一个问题中发现了一个小代码片段,仅使用jquery play() 和pause() 来播放mp3:

<a href="#" rel="http://www.uscis.gov/files/nativedocuments/Track%2093.mp3"
class="play">Play</a>

<div class="pause">Stop</div>

<script>

$(document).ready(function() {
var audioElement = document.createElement('audio');
var source = $('.play').attr('rel');

audioElement.setAttribute('src', source);
//audioElement.setAttribute('autoplay', 'autoplay');
audioElement.load()
$.get();
audioElement.addEventListener("load", function() {
audioElement.play();
}, true);

$('.play').click(function() {
audioElement.play();
});


$('.pause').click(function() {
audioElement.pause();
});
});

我从“播放”链接的 rel 属性中获取音频源。现在我想添加更多音频链接并使源相对于它们的 rel 属性。

我试过了

var source = $(this).attr('rel');

还有.find()和.each(),但到目前为止没有任何效果。我设置了 jsfiddle有两个音频链接,其中仅播放第一个音频文件。 ( fiddle 链接到一个外部脚本,客户端在他的网站上使用该脚本,其中仅加载了 jquery 1.4.3,但我想无论如何都是可能的。我只是不想使用音频播放器插件,我的目标是简约的解决方案。)

任何帮助将不胜感激!

最佳答案

您可以更新脚本,为每个容器创建一个音频标签:

$(document).ready(function () {
// For each container div
$(".container").each(function() {
// Create the HTML5 <audio> tag
var audioElement = document.createElement('audio');
// Find the play/pause buttons
var $play = $(this).find(".play");
var $pause = $(this).find(".pause");
// Load the source from the play button
var source = $play.attr('rel');
audioElement.setAttribute('src', source);
$.get();
// Play the sound when loaded
audioElement.addEventListener("load", function () {
audioElement.play();
}, true);
// When the user clicks on the play button, play the audio
$play.click(function () {
audioElement.play();
});
// When the user clicks on the pause button, pause it
$pause.click(function () {
audioElement.pause();
});
});
});

并更新了 fiddle :http://jsfiddle.net/sY7UT/

关于javascript - 简约的 play() 和pause() 音频解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17657357/

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