Reputation: 72
I need a sample code for click to play music I am getting all of my mp3 files from my system folder and I would like to play that pieces of music.
My code like this
<a href="mp3folder/mp3name.mp3">mp3name</a>
<a href="mp3folder/mp3name1.mp3">mp3name1</a>
<a href="mp3folder/mp3name2.mp3">mp3name2</a>
<a href="mp3folder/mp3name3.mp3">mp3name3</a>
How I should go about this using JavaScript
?
Upvotes: 2
Views: 2425
Reputation: 1569
You can use audio
tag to play the audio, and if you want to pause one audio if another audio file is played here is a simple javascript code
check what are the elements playing right now and pause
the audio which is currently playing.
Read more about audio
tag from MDN
document.addEventListener('play', function(element){
var audios = document.getElementsByTagName('audio');
for(var i = 0, len = audios.length; i < len; i++){
if(audios[i] != element.target){
audios[i].pause();
}
}
}, true);
document.addEventListener('play', function(element){
var audios = document.getElementsByTagName('audio');
for(var i = 0, len = audios.length; i < len; i++){
if(audios[i] != element.target){
// console.log("audio paused");
audios[i].pause();
}
}
}, true);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div>
<a href="#" onclick="document.getElementById('p1').play()">Play 1</a>
<a href="#" onclick="document.getElementById('p2').play()">Play 2</a>
<a href="#" onclick="document.getElementById('p3').play()">Play 3</a>
<a href="#" onclick="document.getElementById('p4').play()">Play 4</a>
</div>
<audio
id="p1"
src="https://soundbible.com/mp3/Tyrannosaurus%20Rex%20Roar-SoundBible.com-807702404.mp3">
Your browser does not support the <code>audio</code> element.
</audio>
<audio
id="p2"
src="https://soundbible.com/mp3/Tyrannosaurus%20Rex%20Roar-SoundBible.com-807702404.mp3">
Your browser does not support the <code>audio</code> element.
</audio>
<audio
id="p3"
src="https://soundbible.com/mp3/Tyrannosaurus%20Rex%20Roar-SoundBible.com-807702404.mp3">
Your browser does not support the <code>audio</code> element.
</audio>
<audio
id="p4"
src="https://soundbible.com/mp3/Tyrannosaurus%20Rex%20Roar-SoundBible.com-807702404.mp3">
Your browser does not support the <code>audio</code> element.
</audio>
<audio
id="p5"
src="https://soundbible.com/mp3/Tyrannosaurus%20Rex%20Roar-SoundBible.com-807702404.mp3">
Your browser does not support the <code>audio</code> element.
</audio>
</body>
</html>
Source: multiple audio html : auto stop other when current is playing with javascript
Upvotes: 2