autoplay.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*!
  2. {
  3. "name": "Audio Autoplay",
  4. "property": "audioautoplay",
  5. "authors": ["Jordy van Dortmont"],
  6. "tags": ["audio"],
  7. "async": true
  8. }
  9. !*/
  10. /* DOC
  11. Checks for support of the autoplay attribute of the audio element.
  12. */
  13. define(['Modernizr', 'addTest', 'docElement', 'createElement', 'test/audio'], function(Modernizr, addTest, docElement, createElement) {
  14. Modernizr.addAsyncTest(function() {
  15. var timeout;
  16. var waitTime = 200;
  17. var retries = 5;
  18. var currentTry = 0;
  19. var elem = createElement('audio');
  20. var elemStyle = elem.style;
  21. function testAutoplay(arg) {
  22. currentTry++;
  23. clearTimeout(timeout);
  24. var result = arg && arg.type === 'playing' || elem.currentTime !== 0;
  25. if (!result && currentTry < retries) {
  26. // Detection can be flaky if the browser is slow, so lets retry in a little bit
  27. timeout = setTimeout(testAutoplay, waitTime);
  28. return;
  29. }
  30. elem.removeEventListener('playing', testAutoplay, false);
  31. addTest('audioautoplay', result);
  32. // Cleanup, but don't assume elem is still in the page -
  33. // an extension may already have removed it.
  34. if (elem.parentNode) {
  35. elem.parentNode.removeChild(elem);
  36. }
  37. }
  38. // Skip the test if audio itself, or the autoplay element on it isn't supported
  39. if (!Modernizr.audio || !('autoplay' in elem)) {
  40. addTest('audioautoplay', false);
  41. return;
  42. }
  43. elemStyle.position = 'absolute';
  44. elemStyle.height = 0;
  45. elemStyle.width = 0;
  46. try {
  47. if (Modernizr.audio.mp3) {
  48. elem.src = 'data:audio/mpeg;base64,/+MYxAAAAANIAUAAAASEEB/jwOFM/0MM/90b/+RhST//w4NFwOjf///PZu////9lns5GFDv//l9GlUIEEIAAAgIg8Ir/JGq3/+MYxDsLIj5QMYcoAP0dv9HIjUcH//yYSg+CIbkGP//8w0bLVjUP///3Z0x5QCAv/yLjwtGKTEFNRTMuOTeqqqqqqqqqqqqq/+MYxEkNmdJkUYc4AKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq';
  49. }
  50. else if (Modernizr.audio.wav) {
  51. elem.src = 'data:audio/wav;base64,UklGRjQAAABXQVZFZm10IBAAAAABAAEAEAAAABAAAAABAAgAZGF0YRAAAAB/f39/f39/f39/f39/f39/';
  52. }
  53. else {
  54. addTest('audioautoplay', false);
  55. return;
  56. }
  57. }
  58. catch (e) {
  59. addTest('audioautoplay', false);
  60. return;
  61. }
  62. elem.setAttribute('autoplay', '');
  63. elemStyle.cssText = 'display:none';
  64. docElement.appendChild(elem);
  65. // Wait for the next tick to add the listener, otherwise the element may
  66. // not have time to play in high load situations (e.g. the test suite)
  67. setTimeout(function() {
  68. elem.addEventListener('playing', testAutoplay, false);
  69. timeout = setTimeout(testAutoplay, waitTime);
  70. }, 0);
  71. });
  72. });