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?
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:
There will be no inconsistent/asynchronous issue.
Also see:
TJ_Tsai / [email protected]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With