js仿微信语音播放

html结构如下:

 <div class="app-voice-you" voiceSrc="xx.mp3">
<img class="app-voice-headimg" src="xx.png" />
<div style="width: 60%;" class="app-voice-state-bg">
<div class="app-voice-state app-voice-pause"></div>
</div>
<div class="app-voice-time app-voice-unread">
1'6"
</div>
</div> <!--语音播放控件-->
<audio id="audio_my" src="">
Your browser does not support the audio tag.
</audio>

核心功能就是语音播放,主要包括了以下几个功能点:

红点表明未听语音,语音听过后,红点会消失;

将“未读”状态的样式独立出来,“已读”的时候,把样式删除就行。结合本地存储处理就搞定了。

 //this是点击的语音的document
var app_voice_time = this.getElementsByClassName("app-voice-time")[0];
if(app_voice_time.className.indexOf("app-voice-unread") != -1){
//存在红点时,把红点样式删除
app_voice_time.className = app_voice_time.className.replace("app-voice-unread","");
}

第一次听语音,会自动播放下一段语音;

这里主要是使用HTML5的audio控件的“语音播放完”事件 
语音播放完,找到下一个语音,播放下一个语音

 //语音播放完事件(PAGE.audio是audio控件的document)
PAGE.audio.addEventListener('ended', function () {
//循环获取下一个节点
PAGE.preVoice = PAGE.currentVoice;
var currentVoice = PAGE.currentVoice;
while(true){
currentVoice = currentVoice.nextElementSibling;//下一个兄弟节点
//已经到达最底部
if(!currentVoice){
PAGE.preVoice.getElementsByClassName("app-voice-state")[0].className = "app-voice-state app-voice-pause";
return false;
}
var voiceSrc = currentVoice.getAttribute("voiceSrc");
if(voiceSrc && voiceSrc != ""){
break;
}
}
if(!PAGE.autoNextVoice){
PAGE.preVoice.getElementsByClassName("app-voice-state")[0].className = "app-voice-state app-voice-pause";
return false;
}
PAGE.currentVoice = currentVoice;
//获取得到下一个语音节点,播放
PAGE.audio.src = voiceSrc;
PAGE.audio.play();
PAGE.Event_PlayVoice();
}, false);

每段语音可以暂停、继续播放、重新播放;

这个比较简单,但是也是比较多逻辑。需要变换样式告诉用户,怎样是继续播放/重新播放。

播放中的语音有动画,不是播放中的语音则会停止动画。

这里主要是CSS3动画的应用

 .app-voice-pause,.app-voice-play{
height: 18px;
background-repeat: no-repeat;
background-image: url(../img/voice.png);
background-size: 18px auto;
opacity: 0.5;
}
.app-voice-you .app-voice-pause{
/*从未播放*/
background-position: 0px -39px;
}
.app-voice-you .app-voice-play{
/*播放中(不需要过渡动画)*/
background-position: 0px -39px;
-webkit-animation: voiceplay 1s infinite step-start;
-moz-animation: voiceplay 1s infinite step-start;
-o-animation: voiceplay 1s infinite step-start;
animation: voiceplay 1s infinite step-start;
}
@-webkit-keyframes voiceplay {
0%,
100% {
background-position: 0px -39px;
}
33.333333% {
background-position: 0px -0px;
}
66.666666% {
background-position: 0px -19.7px;
}
}
上一篇:【反射】利用java反射原理将xml文件中的字段封装成对应的Bean


下一篇:html5的audio实现高仿微信语音播放效果(实际项目)