Chrome上的音频HTML5自动播放

时间:2013-10-23 08:54:18

标签: html5 google-chrome html5-audio

这是我的音频代码:

<audio autoplay >
<source src="sources/audio/pop.ogg" type="audio/ogg">
<source src="sources/audio/pop.mp3" type="audio/mpeg">
</audio>

这在FF中工作正常但在chrome上没有。 如果我添加控件然后它适用于chrome但仍然没有自动播放,我不想要控件。

1 个答案:

答案 0 :(得分:0)

我在Chrome中没有自动播放的视频遇到了同样的问题。 Chrome现在会阻止视频和音频元素中的自动播放。解决方案是将.play()函数延迟1秒。对于您的音频问题,只需将我的代码段中的所有“视频”替换为“音频”。

// Autoplay videos
var playVideos = function () {
  // Get all elements with the video tag
  var videos = document.getElementsByTagName('video');
  // Loop through the videos
  for (i = 0; i < videos.length; i++) {
    // Play video
    videos[i].play();
  } 
};

// Define body variable
var body = document.getElementById('body');
// Wait 1 Second to trick out Chrome
setTimeout(function() {
  // execute the playVideo function
  body.addEventListener('onload', playVideos(), false);
}, 1000);

PS:你需要为你的身体提供id'body'才能使这个片段正常工作。

相关问题