Play mp3 file using javascript onClick

I play an mp3 file, just javascript onClick.

Below is my code:

//Music File 1 <audio id="id1" src="01.mp3"></audio> <button onClick="document.getElementById("id1").play()">Play</button> <button onClick="document.getElementById("id1").pause()">Stop</button> //Music File 2 <audio id="id2" src="02.mp3"></audio> <button onClick="document.getElementById("id2").play()">Play</button> <button onClick="document.getElementById("id2").pause()">Stop</button> 

My question is: I play music 01.mp3 and I want her to stop playing if I press the play button in music 02.mp3.

Can someone give me a better solution than this? In general, I want to play music, for example, www.mp3skull.com, another stop if you click another file to play.

Regards, Virak

+4
source share
2 answers

Besides tag errors (assuming it's just a typo in this post), if you want a more enjoyable Javascript audio player, check out http://jplayer.org/ - this is an open source, free player API.

One of the methods available to the player, .pauseOthers() stops all players on a page other than the one on which you ran the method, useful in your situation.

+5
source

You have html / javascript syntax errors:

 <button onClick="document.getElementById("id2").play()">Play</button> ^ ^ ^ ^ 1 2 3 4 

quote # 2 closes quote # 1, so your id2 is an EXTERNAL onclick statement and is part of the button tag. Same thing for 3 and 4. Instead, change the inner quotation marks to 'id2' .

+4
source

Source: https://habr.com/ru/post/1414513/


All Articles