Skip to content Skip to sidebar Skip to footer

HTML5 Audio: How To Play Only A Selected Portion Of An Audio File (audio Sprite)?

I'm working on an iOS metronome web app. Since mobile Safari can only play one sound at a time, I'm attempting to create an 'audio sprite' - where I can use different segments of a

Solution 1:

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>

Solution 2:

I didn't find a clean function to play segment of an audio object so this is what I come up with. It will also solves the the following error which will occur if the user click multiple triggers within short amount of time.

"Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()"

const audioObj_1 = new Audio('/some_audio_file.m4a');
playSegment(audioObj_1 , 1.11, 2.45); // this will play from 1.11 sec to 2.45 sec

function playSegment(audioObj, start, stop){
    let audioObjNew = audioObj.cloneNode(true); //this is to prevent "play() request was interrupted" error. 
    audioObjNew.currentTime = start;
    audioObjNew.play();
    audioObjNew.int = setInterval(function() {
        if (audioObjNew.currentTime > stop) {
            audioObjNew.pause();
            clearInterval(audioObjNew.int);
        }
    }, 10);
} 

Post a Comment for "HTML5 Audio: How To Play Only A Selected Portion Of An Audio File (audio Sprite)?"