Skip to content

Commit 4c91e8d

Browse files
committed
fix(html5 audio): can't obtain the duration in some browser
1 parent 143ae44 commit 4c91e8d

File tree

1 file changed

+41
-11
lines changed

1 file changed

+41
-11
lines changed

src/howler.core.js

+41-11
Original file line numberDiff line numberDiff line change
@@ -2326,22 +2326,52 @@
23262326
var self = this;
23272327
var parent = self._parent;
23282328

2329-
// Round up the duration to account for the lower precision in HTML5 Audio.
2330-
parent._duration = Math.ceil(self._node.duration * 10) / 10;
2329+
const loadJob = function() {
2330+
// Round up the duration to account for the lower precision in HTML5 Audio.
2331+
parent._duration = Math.ceil(self._node.duration * 10) / 10;
2332+
2333+
// Setup a sprite if none is defined.
2334+
if (Object.keys(parent._sprite).length === 0) {
2335+
parent._sprite = {__default: [0, parent._duration * 1000]};
2336+
}
23312337

2332-
// Setup a sprite if none is defined.
2333-
if (Object.keys(parent._sprite).length === 0) {
2334-
parent._sprite = {__default: [0, parent._duration * 1000]};
2338+
if (parent._state !== 'loaded') {
2339+
parent._state = 'loaded';
2340+
parent._emit('load');
2341+
parent._loadQueue();
2342+
}
2343+
2344+
// Clear the event listener.
2345+
self._node.removeEventListener(Howler._canPlayEvent, self._loadFn, false);
23352346
}
23362347

2337-
if (parent._state !== 'loaded') {
2338-
parent._state = 'loaded';
2339-
parent._emit('load');
2340-
parent._loadQueue();
2348+
// If the duration is already got, fire the event immediately.
2349+
if (self._node.duration) {
2350+
loadJob();
2351+
return;
23412352
}
23422353

2343-
// Clear the event listener.
2344-
self._node.removeEventListener(Howler._canPlayEvent, self._loadFn, false);
2354+
// In some edge cases, the duration can only be obtained after playing
2355+
// try to obtain it a few times
2356+
const maxRetry = 20;
2357+
let retryTime = 0;
2358+
2359+
const timer = setInterval(function() {
2360+
++retryTime;
2361+
2362+
if (retryTime === 1) {
2363+
self._node.play();
2364+
self._node.muted = true;
2365+
}
2366+
if (self._node.duration || retryTime > maxRetry) {
2367+
self._node.pause();
2368+
self._node.currentTime = 0;
2369+
self._node.muted = false;
2370+
clearInterval(timer);
2371+
2372+
loadJob();
2373+
};
2374+
}, 6);
23452375
},
23462376

23472377
/**

0 commit comments

Comments
 (0)