Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 audio: How to quickly stop and restart a clip?

Tags:

html

audio

See title. I am trying to play an audio file 4 times in a row, every 300 milliseconds. However, the clip is longer than 300ms, so it ignores new play requests until the clip is done playing. I'm looking for some way to stop and restart the clip every 300ms.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
</head>
<body>
    <audio id="note0440"><source src="0440.a4.wav" type="audio/wav"></audio>
    <script type="text/javascript">
        function playNote (loop) {
            var n = document.getElementById("note0440")
            if (loop > 4)
                return
            n.volume = 0.05
            // n.currentTime = 0
            n.pause()
            n.play()
            setTimeout("playNote("+(loop + 1)+")", 300)
        }
    </script>
    <div style="margin:50px"><button onclick="playNote(1)">Play Note</button></div>
</body>
</html>

This does not work. It does not stop and restart, whether or not n.currentTime = 0 is used.

Here's a WAV file if you need one for testing: http://popstrip.com/misc/0440.a4.wav

like image 268
user353885 Avatar asked Nov 06 '12 01:11

user353885


2 Answers

from section 4.8.10.6 of the specification

media . duration Returns the length of the media resource, in seconds, assuming that the start of the media resource is at time zero.

Returns NaN if the duration isn't available.

Returns Infinity for unbounded streams.

media . currentTime [ = value ] Returns the official playback position, in seconds.

Can be set, to seek to the given time.

Will throw an InvalidStateError exception if there is no selected media resource or if there is a current media controller.

So the specification does not allow for seeks of less than one second. However, different browsers will all implement it a different way (of course). Some browsers may support this, but getting it to reliably work in all deployed browsers today will be a huge pain in the ass. Assuming that you could issue millisecond seeks, the other issue is that the js interpreter may not be able to fulfill your request in time, i.e. the processing of the seek takes longer than the value of the seek, which would lead to other difficulties.

My advice to you would be to abandon the html5 approach for now if you really need smaller than one second granularity for your seeks, and use a plugin or some code running natively on the host if at all possible.

like image 37
Max DeLiso Avatar answered Sep 19 '22 15:09

Max DeLiso


Wherever you are calling the stop just do the following in the order of -

 n.pause();
 n.currentTime = 0;
 n.play();      
like image 52
Jatin Avatar answered Sep 19 '22 15:09

Jatin