HTMLMediaElement.play() Returns a Promise Sample

Available in Chrome 50+ | View on GitHub | Browse Samples

Background

Many mobile browsers prevent JavaScript from initiating playback of media elements unless it's in response to user interaction.

It's historically been difficult to detect failed playbacks due to mobile browser restrictions, but the new Promise-based interface to the play() method provides a friendly way of detecting whether playback succeeded or failed.

Live Output


HTML Snippet

<audio id="music" src="../audio/techno.wav"></audio>
<button id="play" hidden>Play</button>

JavaScript Snippet

function startPlayback() {
  return document.querySelector('#music').play();
}

ChromeSamples.log('Attempting to play automatically...');

startPlayback().then(function() {
  ChromeSamples.log('The play() Promise fulfilled! Rock on!');
}).catch(function(error) {
  ChromeSamples.log('The play() Promise rejected!');
  ChromeSamples.log('Use the Play button instead.');
  ChromeSamples.log(error);

  var playButton = document.querySelector('#play');
  // The user interaction requirement is met if
  // playback is triggered via a click event.
  playButton.addEventListener('click', startPlayback);
  playButton.hidden = false;
});