0

I am using the Modernizr code as displayed here http://codepen.io/davidgenetic/pen/FmHaD to check if autoplay is supported. This works when the site is viewed the first time on Safari Desktop (v 9.0.1), but fails after that (incorrectly concludes that autoplay is not supported when it is). Deleting the cache, and reloading page makes it work again. On other browsers (Chrome, IE, Firefox, Opera) this works fine. Does anyone know how to solve this problem?

Modernizr.addTest('autoplay', function(){

// Audio file data URIs from comments in
// [this gist](https://gist.github.com/westonruter/253174)
// via [mudcube](https://github.com/mudcube)
var mp3 = 'somesong.mp3';

try {
    var audio = new Audio();
    var src = audio.canPlayType('audio/ogg') ? ogg : mp3;
    audio.autoplay = true;
    audio.volume = 0;

    // this will only be triggered if autoplay works
    audio.addEventListener('play', function() {
        Modernizr.autoplay = true;
      // is there a better way to re-evaluate the html classes added by Modernizr?
      var root = document.getElementsByTagName('html')[0];
      root.classList.remove('no-autoplay');
      root.classList.add('autoplay');

      // or if you're using jQuery:
      // $('html').toggleClass('no-autoplay autoplay');
    }, false);

    audio.src = src;
} catch(e) {
    console.log('[AUTOPLAY-ERROR]', e);
}

return false;});
Digital
  • 29
  • 1
  • 6
  • Not able to replicate with the codepen you provided. Running OSX 10.10.5 With Safari Version 9.0.2 (10601.3.9). Always shows supported for me. – Ohgodwhy Dec 10 '15 at 18:32

1 Answers1

0

The code you found hosted in CodePen titled Modernizr support for autoplay property, has nothing to do with Modernizr. This code was written by Peter Coles back in May 2013, then modified by the CodePen author to have functionality similar to Modernizr.

The latest version of Modernizr (v3) has video autoplay detection. Unfortunately, I do not see anything about audio autoplay detection.

I do see one pull request from GrantPax to add an audioautoplay feature to Modernizr. If it gets approved it should be available in the near future.

In the meantime you could do one of two things:

  1. Look through GrantPax's pull request's code and use it. Note that it likely has not had too much testing yet.
  2. See if anyone has a good non-Modernizr solution.
  3. Use Modernizr's videoautoplay detection. I am guessing that browsers that support video autoplay, will also support audio autoplay. But, this is just a guess, so don't take my word for it.

If you agree with my hypothesis, then the following code should work for you, if you import the latest version of Modernizr with the Video Autoplay feature added.

var audioClip = document.getElementById("myAudio");
if (Modernizr.videoautoplay) {
  audioClip.autoplay = true;
}
audioClip.load();
Community
  • 1
  • 1
Fraser Crosbie
  • 1,672
  • 1
  • 12
  • 21