Skip to content

Commit

Permalink
fix(viewer): Audio can muted autoplay if failed (#1054)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mingze authored and mergify[bot] committed Aug 16, 2019
1 parent 0a210dd commit f55857e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
22 changes: 13 additions & 9 deletions src/lib/viewers/media/MediaBaseViewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -304,27 +304,31 @@ class MediaBaseViewer extends BaseViewer {
*
* @private
* @emits volume
* @return {void}
* @return {Promise}
*/
autoplay() {
// Play may return a promise depening on browser support. This promise
// will resolve when playback starts. If it fails, pause UI should be shown.
// Play may return a promise depending on browser support. This promise
// will resolve when playback starts. If it fails, we mute the video
// and try to play again.
// https://webkit.org/blog/7734/auto-play-policy-changes-for-macos/
const autoPlayPromise = this.mediaEl.play();

if (autoPlayPromise && typeof autoPlayPromise.then === 'function') {
autoPlayPromise
this.handleRate();
return autoPlayPromise
.then(() => {
this.handleRate();
this.handleVolume();
})
.catch(() => {
this.pause();
// Auto-play was prevented, try muted play
this.setVolume(0);
this.mediaEl.play();
});
} else {
// Fallback to traditional autoplay tag if play does not return a promise
this.mediaEl.autoplay = true;
}

// Fallback to traditional autoplay tag if play does not return a promise
this.mediaEl.autoplay = true;
return Promise.resolve();
}

/**
Expand Down
9 changes: 9 additions & 0 deletions src/lib/viewers/media/__tests__/MediaBaseViewer-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,15 @@ describe('lib/viewers/media/MediaBaseViewer', () => {
media.autoplay();
expect(media.mediaEl.autoplay).to.be.true;
});

it('should muted autoplay if the promise is rejected', done => {
sandbox.stub(media, 'setVolume');
media.mediaEl.play = sandbox.stub().returns(Promise.reject());
media.autoplay().then(() => {
expect(media.setVolume).to.be.calledWith(0);
done();
});
});
});

describe('loadUI()', () => {
Expand Down

0 comments on commit f55857e

Please sign in to comment.