'On click play a section of a mp3
I have many buttons playing many different sounds - each button plays a different mp3 when clicked. Example code:
<a onclick="this.firstChild.play()"><audio src="1.mp3" ></audio>1</a>
For mobile devices I am trying to play all the different sounds from the same mp3 file, so I can preload 1 file and have more instant experience.
So I would need to set the starting point and end point of the mp3 to be played when clicked.
How do I do that using audio html5 or javascript? Working in just chrome is enough...
Solution 1:[1]
If i got your question right, you want to play different time stamp of a audio file simultaneously or whenever you want
here is one example which you can use
<a onclick="this.firstChild.play()"><audio id="audio2"
preload="auto"
src="http://cld3097web.audiovideoweb.com/va90web25003/companions/Foundations%20of%20Rock/5.01.mp3#t=00:00:00"
>
</audio>Part 1
</a>
<a onclick="this.firstChild.play()"><audio id="audio2"
preload="auto"
src="http://cld3097web.audiovideoweb.com/va90web25003/companions/Foundations%20of%20Rock/5.01.mp3#t=00:00:56" >
</audio>Part 2
</a>
<a onclick="this.firstChild.play()"><audio id="audio2"
preload="auto"
src="http://cld3097web.audiovideoweb.com/va90web25003/companions/Foundations%20of%20Rock/5.01.mp3#t=00:01:00" >
</audio>Part 3
</a>
you can also give time in seconds instead of timestamp like
<a onclick="this.firstChild.play()"><audio id="audio2"
preload="auto"
src="http://cld3097web.audiovideoweb.com/va90web25003/companions/Foundations%20of%20Rock/5.01.mp3#t=0"
>
</audio>Part 1
</a>
<a onclick="this.firstChild.play()"><audio id="audio2"
preload="auto"
src="http://cld3097web.audiovideoweb.com/va90web25003/companions/Foundations%20of%20Rock/5.01.mp3#t=56" >
</audio>Part 2
</a>
<a onclick="this.firstChild.play()"><audio id="audio2"
preload="auto"
src="http://cld3097web.audiovideoweb.com/va90web25003/companions/Foundations%20of%20Rock/5.01.mp3#t60" >
</audio>Part 3
</a>
Solution 2:[2]
I haven't tested this code, but this should work:
<a id="audioTag1"><audio src="1.mp3" ></audio>1</a>
var canPlay = false;
var audio = document.getElementsByTagName('audio')[0];
document.getElementById('audioTag1').addEventListener('click', function(){
playAudio(15);
});
audio.addEventListener('canplay', function() { // listen for the `canplay`event, to make sure the file is loaded.
canPlay = true; // Set a boolean to "true" once the audio has loaded.
});
function playAudio(time){
audio.currentTime = time; // jump to 15 secs into the file
audio.play(); // I'm not certain if this line is necessary.
}
Make sure you run the JS code in a onload event listener, so the audio tag is loaded when the code is executed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TechnoTech |
| Solution 2 |
