Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent seeking in HTML5 Audio player

I want to play audio starting at a specific timestamp. But I can't even get the simplest example to work right. I tried the following, and also modifying w3school's example.

<body>
    <audio src="skyfall.mp3" id="audio" controls preload></audio>
    <button onclick="play()">Play</button>
</body>
<script type="text/javascript">
    var secs = 32;
    function play(){

        var p = document.getElementById("audio");
        p.currentTime = secs;
        console.log('Playing at secs: ' + secs); 
        p.play();
    }
</script>

But different audio plays on each browser: Chrome for Windows is about 4 seconds late, Chrome for Android seems spot-on, Mobile Safari is off. (Even VLC has this issue when playing the file.) If playback starts from the beginning of the file, they stay in sync.

So it looks to me like the HTML5 audio standard is either incorrectly implemented or poorly explained.

I've read that server-side support is sometimes to blame, but I'm unsure how this would be an issue when I'm reading local files. Ultimately I want to get this working in a Cordova project.

Any ideas?

like image 892
Chris Backofen Avatar asked Aug 21 '15 15:08

Chris Backofen


2 Answers

I met the same issue, and I solved it by converting my MP3 file to the CBR(Constant Bit Rate) format. Then, it can solve the inconsistent issue between the currentTime and the real sound.

Choose the CBR format


Steps:

  • Download and install "Audacity" (it's a free for any platform)
  • Open your MP3 file
  • Click [File] -> [Export] -> [Options] -> [Constant] (See: Converting MP3 to Constant Bit Rate)
  • Audacity will ask you to provide the LAME MP3 encoder (See: [download and install the LAME MP3 encoder])

There will be no inconsistent/asynchronous issue.


Also see:

  • HTML5 audio starts from the wrong position in Firefox
  • Inconsistent seeking in HTML5 Audio player

TJ_Tsai / [email protected]

like image 50
蔡宗容 Avatar answered Oct 06 '22 10:10

蔡宗容


The issue is with file encoding. For MP3 files, only constant bit rate seeking works correctly/consistently across all browsers. W3 says that MP3 is the only format officially universally supported by all browsers, so I think using CBR MP3s is the answer. That said, Mozilla has a more in-depth guide on format support.

When the bit rate is not constant, browsers seek to different segments of audio given the same timestamp. The algorithm to seek is simple for constant bit rate, but is more complex for variable bit rate (and often involves some form of estimation); I couldn't find a definition of this operation in the HTML standard, so it's unsurprising different browsers implement this differently.

This answer has some more discussion and potential workarounds.

like image 44
Chris Backofen Avatar answered Oct 06 '22 10:10

Chris Backofen