Javascript Repeating Audio

℡╲_俬逩灬. 提交于 2019-12-07 22:41:04

问题


I have been trying to get this JavaScript to repeat the audio once it has finished, I have had a look around and I am inexperienced with JavaScript, although I have made attempts tweaking and researching I have had no luck so far.

I would be very grateful for any help and tips

Many thanks- Grant

<!-- Script inside body -->

    <!-- Audio Player -->
        <script>
        $(document).ready(function() {
        var audioElement = document.createElement('audio');
        audioElement.setAttribute('src', 'music/audio.mp3');
        audioElement.setAttribute('play', 'autoplay');
        //audioElement.load()
        $.get();
        audioElement.addEventListener("load", function() {
        audioElement.play();
        audioElement.loop();
        }, true);


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


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

    });
        </script>

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

回答1:


Set loop property for repeat track:

audioElement.loop = true



回答2:


Some browser doesn't support the loop propperty/attribute to audio. In this, you can add event listener instead like:

var myAudio = document.createElement('audio');
myAudio.setAttribute('src', 'test.mp3');
myAudio.play()
myAudio.addEventListener('ended', function() {
    this.currentTime = 0;
    this.play();
}, false);


来源:https://stackoverflow.com/questions/17890319/javascript-repeating-audio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!