HTML5 Audio: How to Play only a Selected Portion of an Audio File (audio sprite)?
I think there are a couple of problems here.
Firstly, you're adding an event listener every time the user clicks Play 1.
Also I think
if (currentTime >= 0.5) { ...
should be
if (audio.currentTime >= 0.5) { ...
This also works:
<audio id="sample" src="http://dl.dropbox.com/u/222645/click1sec.mp3" controls preload></audio>
<a href="javascript:playSegment(0.0, 0.5);">Play1</a>
<a href="javascript:playSegment(0.5);">Play2</a>
<script>
var audio = document.getElementById('sample');
var segmentEnd;
audio.addEventListener('timeupdate', function (){
if (segmentEnd && audio.currentTime >= segmentEnd) {
audio.pause();
}
console.log(audio.currentTime);
}, false);
function playSegment(startTime, endTime){
segmentEnd = endTime;
audio.currentTime = startTime;
audio.play();
}
</script>