首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >极简播放()和暂停()音频解决方案

极简播放()和暂停()音频解决方案
EN

Stack Overflow用户
提问于 2013-07-15 15:00:20
回答 1查看 362关注 0票数 3

我在另一个问题中找到了一个小代码片段,只使用jquery ()和pause()播放一个mp3:

代码语言:javascript
运行
复制
<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();
    });
});

我从"play"-link的rel属性获得音频源。现在,我想添加更多的音频链接,并使源相对于它们的rel属性。

我试过了

代码语言:javascript
运行
复制
var source = $(this).attr('rel');

还有.find()和.each(),但是到目前为止还没有起作用。我已经设置了一个jsfiddle与两个音频链接,其中只有第一个音频文件将被播放。(小提琴链接到外部脚本,客户端在其站点上使用该脚本,其中只加载jQuery1.4.3,但我认为这是可能的。我只是不想使用音频播放器插件,我的目标是一个极简的解决方案。)

任何帮助都将不胜感激!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-15 15:04:42

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

代码语言:javascript
运行
复制
$(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/

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17657357

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档