user2340767
user2340767

Reputation: 527

Play audio and restart it onclick

I'm looking to restart an audio file in a HTML5 audio player. I have defined a audio file and a play button.

<audio id="audio1" src="01.wav"></audio>
<button onClick="play()">Play</button>

When I click the play button the audio file starts playing, but when I click the button again the audio file doesn't stop and will not play again until it reaches the end of the file.

function play() {
    document.getElementById('audio1').play();
}

Is there a method that would allow me to restart the audio file when I click the button using onclick rather than waiting for the song to stop?

Upvotes: 31

Views: 66999

Answers (3)

Singhak
Singhak

Reputation: 8896

function sound(src) {
    this.sound = document.createElement("audio");
    this.sound.src = src;
    this.sound.setAttribute("preload", "auto");
    this.sound.setAttribute("controls", "none");
    //this.sound.style.display = "none";
    document.body.appendChild(this.sound);
    this.play = function () {
        this.sound.play();
    }
    this.stop = function () {
        this.sound.pause();
        this.sound.currentTime = 0
    }
}

you can use the /above function to play sound

 let mysound1 = new sound('xyz.mp3')
 mysound1.play()

Upvotes: 0

Deepti Gehlot
Deepti Gehlot

Reputation: 617

soundManager.setup({
preferFlash: false,
//, url: "swf/"
onready: function () {
    soundManager.createSound({
        url: [
            "http://www.html5rocks.com/en/tutorials/audio/quick/test.mp3", "http://www.html5rocks.com/en/tutorials/audio/quick/test.ogg"
        ],
        id: "music"
    });
    soundManager.createSound({
        url: [
            "http://www.w3schools.com/html/horse.mp3", 
        ],
        id: "horse"
    });
    soundManager.play("music"); 
}

}).beginDelayedInit();

And to start horse and pause all other sounds currently playing in a click event:

$("#horse").click(function () {
soundManager.stopAll();
soundManager.play("horse");

});

Upvotes: 1

adeneo
adeneo

Reputation: 318182

To just restart the song, you'd do:

function play() {
    var audio = document.getElementById('audio1');
    if (audio.paused) {
        audio.play();
    }else{
        audio.currentTime = 0
    }
}

FIDDLE

To toggle it, as in the audio stops when clicking again, and when click another time it restarts from the beginning, you'd do something more like :

function play() {
    var audio = document.getElementById('audio1');
    if (audio.paused) {
        audio.play();
    }else{
        audio.pause();
        audio.currentTime = 0
    }
}

FIDDLE

Upvotes: 70

Related Questions