Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

javascript - Play one HTML audio element at a time

I have many audio elements on a single page and I want to play just one element at a time. That is if one audio element is playing and I click on play on another element, the previous audio element should pause.

I found a jQuery code from another question to do this but that uses an image as play/pause controls. I'm using the inbuilt controls='controls' attribute for the audio element instead. Is it possible to use jQuery to control the play/pause feature for the audio element in my case?

Here is my HTML code

<div>
    <p class="song"><h3><strong>#1 Intro - The Oath</strong></h3><p>
    <audio class="playback" src=http://geo-samples.beatport.com/lofi/5005876.LOFI.mp3 controls='controls' preload="none">
        <I>Your browser does not support the audio element.</I>
    </audio>
</div>

<div>
    <p class="song"><h3><strong>#2 A State Of Trance Year Mix 2013</strong></h3></p>
    <audio class="playback" src=http://geo-samples.beatport.com/lofi/5005933.LOFI.mp3 controls='controls' preload="none">
        <I>Your browser does not support the audio element.</I>
     </audio>
</div>

Here is the jQuery code

$(document).ready(function() {
    var curPlaying;

    $(function() {
        $(".playback").click(function(e) {
            e.preventDefault();
            var song = $(this).next('audio')[0];
            if(song.paused){
                song.play();
                if(curPlaying) $("audio", "#"+curPlaying)[0].pause();
            } else { song.pause(); }
            curPlaying = $(this).parent()[0].id;
        });
    });
});

The jQuery code doesn't seem to be working for me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
$(function(){
    $("audio").on("play", function() {
        $("audio").not(this).each(function(index, audio) {
            audio.pause();
        });
    });
});

See sample at JSFiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...