极简主义播放()和贫困()音频解决方案

Minimalistic play() and pause() audio solution

本文关键字:音频 解决方案 播放      更新时间:2023-09-26

我在另一个问题中发现了一个小代码片段,只使用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/