web端实现类微信的语音播放效果

最近做了个web端的语音播放效果,实现起来很简单,但中间因为参考文章问题,实现部分功能上也是费了很大力气

效果如下:

 

web端实现类微信的语音播放效果_第1张图片

 

 

先说需求:

1. 点击播放,显示动画

2. 暂停播放,停止动画

3. 切换播放, 停止上一个动画,显示当前动画

4. 播放结束,停止动画

 1、2、3 实现都很简单

实现4时,参考了网上的文章【点击打开链接】,用了定时器,不好实现、效率低、bug也多

用定时器的bug:

      暂停播放时,应不应该clearTimeOut() ?  清除定时器的话,再次点击播放时,setTimeout的时间是多少? 不好获取吧,时间设置不对会导致,音乐与动画播放不同步

 

最终实现:

参考了w3c上audio的事件属性,轻松实现

控制播放暂停:

var curPlayId = null; // 当前播放语音标识
function addAudioEvent() {
  $('.yuyin').click(function () {
  	var $this = $(this); 
    var $audio = $this.children("audio")[0];
  	if (curPlayId == null) {
      $audio.play();
  	  curPlayId = $this.attr('id');
  	} else {
  	  if ($this.attr('id') == curPlayId) { // 点击当前播放中的语音,暂停播放
        $audio.pause();
        curPlayId = null;
  	  }	else {
  	  	// 先暂停当前播放语音 
        $('#' + curPlayId).children("audio")[0].pause();
  	  	// 播放点击语音
        $audio.play();
  	  	curPlayId = $this.attr('id');
  	  } 	
  	} 	
  });
}

audio事件监听--改变动画:

$('audio').bind('play', function() {
    $(this).next().css('animation-play-state', 'running');
  });
  $('audio').bind('ended', function() {
    $(this).next().css('animation-play-state', 'paused');
  });
  $('audio').bind('pause', function() {
    $(this).next().css('animation-play-state', 'paused');
  });

页面元素:

<$= msg.fileParam $>''

样式:

.yuyin{
    margin: .1rem 0;
    color: #999999;
    height: 34px;
    max-width: 200px;
    min-width: 80px;
    background-color: #e8f8e6;
    border: 1px solid #e0e0e0;
    border-radius: 6px; 
    position: relative;
  }

  /* 右侧样式 */
  .yuyin_img{
    position: absolute;
    width: 30px;
    height: 34px;
    background: url(//static.xxt.cn/nb/zx/message/img/yuyin.png);
    background-size: 115px 34px;
    background-repeat: no-repeat;
    background-position: -3px;
    animation: bofang 1s steps(1) infinite;
    -moz-animation: bofang 1s steps(1) infinite; 
    -webkit-animation: bofang 1s steps(1) infinite; 
    -o-animation: bofang 1s steps(1) infinite;
    animation-play-state: paused;
  }

  .yuyin_img_l{
    left: 5px;
  }
  .yuyin_img_r{
    right: 5px;
    transform: rotate(180deg);
  }
  .yuyin_txt{
    position: absolute;
    color: lightgray;
    line-height: 34px;
  }
  .yy_txt_r{
    left: 5px;
  }
  .yy_txt_l{
    right: 5px;
  }
  @keyframes bofang
  {
    25%  {background-position: -33px;}
    50%  {background-position: -59px;}
    75%  {background-position: -84px;} 
    100% {background-position: 0px;}
  }

【语音图标的图片是合并过的图片】

 

 

你可能感兴趣的:(前端开发)