Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play audio and restart it onclick

Tags:

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?

like image 881
user2340767 Avatar asked Jul 14 '13 03:07

user2340767


People also ask

How do I add sound to onclick in HTML?

Audio play() Method The play() method starts playing the current audio. Tip: This method is often used together with the pause() method. Tip: Use the controls property to display audio controls (like play, pause, seeking, volume, etc, attached on the audio).

How do you play sound on click react?

To play an mp3 clip on click in React, we can use the Audio constructor to create an audio element with the MP3 file URL. Then we call play on the created object to play the audio clip. We create the audio object with the Audio constructor with the MP3 file URL as its argument. Then we call audio.


2 Answers

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

like image 194
adeneo Avatar answered Sep 28 '22 04:09

adeneo


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"); 

});

like image 37
Deepti Gehlot Avatar answered Sep 28 '22 04:09

Deepti Gehlot