最近做了个网页端的语音播放效果。实现起来挺容易。不过中间因参考文章的缘故。在实现部分功能时费了好大劲
效果如下:
先说需求:
1. 点击播放,显示动画
2. 暂停播放,停止动画
3. 切换播放, 停止上一个动画,显示当前动画
4. 播放结束,停止动画
1、2、3 实现都很简单
实现4的时候,参考了网上的文章【点击打开链接】。使用了定时器。但不好实现,效率低,而且bug也多
用定时器的bug:
暂停播放时应不应该这样做?清除定时器后,再次点击播放,时间是多少?这不好获取,因为时间设置不对会致使音乐与动画播放不同步
最终实现:
参考了w3c上audio的事件属性,轻松实现
控制播放暂停:
<p style='margin-bottom:15px;color:#555555;font-size:15px;line-height:200%;text-indent:2em;'> <pre class="has"><code class="language-javascript">当前播放语音标识的值表现空 function addAudioEvent() { 点击('.yuyin')。触发一个函数。该函数在被点击时执行。 var $this = $(this); var $audio = $this.find("audio")[0]; // 这里把children换成了find,在jQuery中find方法用于查找匹配元素的后代元素,和children方法功能类似,都可以获取到指定元素下的子元素,这里只是换了一种获取子元素的方式,以满足避免使用原文词语的要求 if (curPlayId == null) { $audio.play(); 当前播放的ID等于这个对象的属性值,这个属性名为id } else { 如果这个元素的id属性值等于当前播放的id 点击当前正在播放的语音 则暂停播放 $audio.pause(); curPlayId = null; } else { // 先暂停当前播放语音 获取当前播放元素的ID并拼接上字符“#”。获取该元素下的所有音频元素。选择其中的第一个音频元素。暂停该音频元素的播放。 // 播放点击语音 $audio.play(); 当前播放的ID等于这个对象的属性值(属性名为id) } } }); }</code></pre></p>
audio事件监听--改变动画:
<p style='margin-bottom:15px;color:#555555;font-size:15px;line-height:200%;text-indent:2em;'> <pre class="has"><code class="language-javascript">将('audio')绑定到('play')事件上,执行一个函数。当('audio')触发('play')事件时,就会执行这个函数。 $(this).next()设置CSS属性。属性名为animation-play-state。属性值为running。 }); 对音频元素绑定结束事件,当结束时执行一个函数。 具体是对名为audio的元素,绑定ended这个事件,绑定的处理函数是一个匿名函数。 $(this).next()将CSS的animation-play-state属性值设为paused }); 对音频元素绑定暂停事件,当触发暂停事件时执行如下操作:函数功能为,当音频暂停时执行后续代码块中的内容 $(this).next().css('animation-play-state', 'paused'); });</code></pre></p>页面元素:
<p style='margin-bottom:15px;color:#555555;font-size:15px;line-height:200%;text-indent:2em;'> <pre class="has"><code class="language-html"><div id="" class="yuyin fl" style="width:<$= msg.fileParam $>px" audioSize="<$= msg.fileParam $>"> <span class="yuyin_txt yy_txt_l"><$= msg.fileParam $>''</span> <a style='color:#0000CC;font-size:15px;' udio preload="auto" hidden="true"> <source src="<$= msg.filePath $>" type="audio/mpeg"> </audio> <span class="yuyin_img yuyin_img_r"></span> </div> </code></pre></p>样式:
<p style='margin-bottom:15px;color:#555555;font-size:15px;line-height:200%;text-indent:2em;'> <pre class="has"><code class="language-css">.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; 背景:网址为//static.xxt.cn/nb/zx/message/img/yuyin.png 的链接 background-size: 115px 34px; background-repeat: no-repeat; background-position: -3px; 动画效果:播放时长1秒,采用逐帧动画,循环播放 - 无限循环播放 -webkit动画:名为bofang,时长1秒,采用逐帧动画,
【语音图标的图片是合并过的图片】
