Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Repeating Audio

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>
like image 796
Grant Avatar asked Jan 18 '26 16:01

Grant


2 Answers

Set loop property for repeat track:

audioElement.loop = true
like image 134
Mihail Avatar answered Jan 20 '26 08:01

Mihail


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);
like image 36
aldrien.h Avatar answered Jan 20 '26 09:01

aldrien.h



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!