Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(viewer): Pause audio instead of muting it if autoplay is prevented #1068

Merged
merged 9 commits into from
Sep 17, 2019
Merged
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.
mxiao6 marked this conversation as resolved.
Show resolved Hide resolved
*
* @override
* @emits volume
* @return {Promise}
*/
autoplay() {
mxiao6 marked this conversation as resolved.
Show resolved Hide resolved
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();
mxiao6 marked this conversation as resolved.
Show resolved Hide resolved
})
.catch(() => {
// Auto-play was prevented, try muted play
this.setVolume(0);
this.mediaEl.play();
this.mediaEl
.play()
.then(() => {
mxiao6 marked this conversation as resolved.
Show resolved Hide resolved
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();
});
});
});
});