Skip to content

Commit

Permalink
fix(viewer): Pause audio instead of muting it if autoplay is prevented
Browse files Browse the repository at this point in the history
  • Loading branch information
Mingze Xiao committed Sep 11, 2019
1 parent 7c6a491 commit d14777a
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 2 deletions.
27 changes: 27 additions & 0 deletions src/lib/viewers/media/MP3Viewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,33 @@ class MP3Viewer extends MediaBaseViewer {
this.mediaControls.show();
this.mediaControls.resizeTimeScrubber();
}

/**
* Determines if media should autoplay based on cached settings value.
*
* @override
* @emits volume
* @return {Promise}
*/
autoplay() {
const autoPlayPromise = this.mediaEl.play();

if (autoPlayPromise && typeof autoPlayPromise.then === 'function') {
return autoPlayPromise
.then(() => {
this.handleRate();
this.handleVolume();
})
.catch(() => {
// Auto-play was prevented, pause
this.mediaEl.pause();
});
}

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

export default MP3Viewer;
11 changes: 9 additions & 2 deletions src/lib/viewers/media/MediaBaseViewer.js
Original file line number Diff line number Diff line change
Expand Up @@ -317,15 +317,22 @@ class MediaBaseViewer extends BaseViewer {
const autoPlayPromise = this.mediaEl.play();

if (autoPlayPromise && typeof autoPlayPromise.then === 'function') {
this.handleRate();
return autoPlayPromise
.then(() => {
this.handleRate();
this.handleVolume();
})
.catch(() => {
// Auto-play was prevented, try muted play
this.setVolume(0);
this.mediaEl.play();
this.mediaEl
.play()
.then(() => {
this.handleRate();
})
.catch(() => {
this.mediaEl.pause();
});
});
}

Expand Down
13 changes: 13 additions & 0 deletions src/lib/viewers/media/__tests__/MP3Viewer-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,17 @@ describe('lib/viewers/media/MP3Viewer', () => {
mp3.loadUI();
});
});

describe('autoplay()', () => {
it('should pause autoplay if the promise is rejected', done => {
mp3.mediaEl = {
play: sandbox.stub().returns(Promise.reject()),
pause: sandbox.stub(),
};
mp3.autoplay().then(() => {
expect(mp3.mediaEl.pause).to.be.called;
done();
});
});
});
});

0 comments on commit d14777a

Please sign in to comment.