audio小记

写H5活动页的需要音频,图标旋转停止保持当时的旋转角度,这样视觉体验效果好;

之前写法是点击pause()就直接停止动画,后来发现了animation有个比较好的属性animation-play-state:runnimg/paused可以让图标保持当前旋转角度;

以下是相关代码,比较简单,大神可以过,像我一样的小白,可以共同学习;

注意:

1、我测试用的是chrome浏览器,chrome浏览器现在是限制了音频以及视频无法自动播放;

在chrome 浏览器中输入:chrome://flags,搜索“Autoplay policy”,默认为“Default”,

修改为 “No user gesture is required” 就可以了;此方法仅限谷歌浏览器,

2、在微信浏览器中打开也不会自动播放,目前我的解决办法是:监听微信的接口

//微信端自动播放音频
document.addEventListener("WeixinJSBridgeReady", function() {
  audio.play();
}, false);

HTML

<div class="audio">
      <audio id="audioTag" src="音频地址" autoplay="autoplay" controls="controls" loop='false' hidden="true">您的浏览器暂不支持audio</audio>
</div>

CSS

/* 音频 */
.audio {
  position:absolute;top:60/50rem;right:60/50rem;z-index:99;width:70/50rem;height:70/50rem;background:url(images/music.png) top center no-repeat; background-size:100% 100%;
  animation:turn 1s linear infinite running;
  -webkit-animation:turn 1s linear infinite running;
}
.paused{
  animation-play-state: paused;
  -webkit-animation-play-state: paused;
}
/* 音频动画 */
@keyframes turn{
  0%{transform:rotate(0)};
  100%{transform:rotate(1turn)}
}

@-webkit-keyframes turn{
  0%{transform:-webkit-rotate(0)};
  100%{transform:-webkit-rotate(1turn)}
}

JS

//音频自动播放
var audio = $('#audioTag').get(0);
var controlsPlay = $('.audio');
controlsPlay.click(function() {
  //改变暂停/播放icon
  if (audio.paused) {
    audio.play();
    $(this).removeClass('paused')

  } else {
    audio.pause();
    $(this).addClass('paused')
  }
});

//微信端自动播放音频 document.addEventListener(
"WeixinJSBridgeReady", function() { audio.play(); }, false);

***audio在ios中禁止了autoplay属性,无法自动播放 ,找了很久看到大多数使用touchstart事件触发play()事件

目前还是没有比较好的解决方案,我最后的解决方案是ios不自动播放通过touchstart触发,android自动播放

Complete!

原文地址:https://www.cnblogs.com/hongll/p/10396648.html