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
641 views
in Technique[技术] by (71.8m points)

jquery - HTML5 Audio - Sound only plays once

I am using Chrome and this is my code:

<audio id="letter_audio" src="audio/bomb.mp3" type="audio/mp3" preload="auto"></audio>

    $('.sound').live('click', function () {

        var sound = $("#letter_audio")[0];  

        sound.pause();
        sound.currentTime = 0;
        sound.play();

        return false;
    });

How come the sound plays the first time I click on play. then when I click again, it pauses, like the code goes. but the it justs stays on pause? i want it to play, then when i click on it again, go back to 0 and play again as in the code?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I've had similar problems replaying audio, but managed to solve it by calling the load() method before the play() call. Try this:

$('.sound').live('click', function () {
    var sound = $("#letter_audio")[0];

    sound.load();
    sound.play();

    return false;
});

I think this is better than resetting the src attribute for two reasons:

  1. Keeps the src value in the page content, rather than in the JavaScript
  2. Works when you embed multiple <source> elements of different audio formats:

    <audio id="letter_audio">
       <source src="audio/bomb.mp3" type="audio/mp3" preload="auto"/>
       <source src="audio/bomb.ogg" type="audio/ogg" preload="auto"/>
    </audio>
    

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

...