html结构如下:
1 <div class="app-voice-you" voiceSrc="xx.mp3"> 2 <img class="app-voice-headimg" src="xx.png" /> 3 <div style=" 60%;" class="app-voice-state-bg"> 4 <div class="app-voice-state app-voice-pause"></div> 5 </div> 6 <div class="app-voice-time app-voice-unread"> 7 1'6" 8 </div> 9 </div> 10 11 <!--语音播放控件--> 12 <audio id="audio_my" src=""> 13 Your browser does not support the audio tag. 14 </audio>
核心功能就是语音播放,主要包括了以下几个功能点:
红点表明未听语音,语音听过后,红点会消失;
将“未读”状态的样式独立出来,“已读”的时候,把样式删除就行。结合本地存储处理就搞定了。
1 //this是点击的语音的document 2 var app_voice_time = this.getElementsByClassName("app-voice-time")[0]; 3 if(app_voice_time.className.indexOf("app-voice-unread") != -1){ 4 //存在红点时,把红点样式删除 5 app_voice_time.className = app_voice_time.className.replace("app-voice-unread",""); 6 }
第一次听语音,会自动播放下一段语音;
这里主要是使用HTML5的audio控件的“语音播放完”事件
语音播放完,找到下一个语音,播放下一个语音
1 //语音播放完事件(PAGE.audio是audio控件的document) 2 PAGE.audio.addEventListener('ended', function () { 3 //循环获取下一个节点 4 PAGE.preVoice = PAGE.currentVoice; 5 var currentVoice = PAGE.currentVoice; 6 while(true){ 7 currentVoice = currentVoice.nextElementSibling;//下一个兄弟节点 8 //已经到达最底部 9 if(!currentVoice){ 10 PAGE.preVoice.getElementsByClassName("app-voice-state")[0].className = "app-voice-state app-voice-pause"; 11 return false; 12 } 13 var voiceSrc = currentVoice.getAttribute("voiceSrc"); 14 if(voiceSrc && voiceSrc != ""){ 15 break; 16 } 17 } 18 if(!PAGE.autoNextVoice){ 19 PAGE.preVoice.getElementsByClassName("app-voice-state")[0].className = "app-voice-state app-voice-pause"; 20 return false; 21 } 22 PAGE.currentVoice = currentVoice; 23 //获取得到下一个语音节点,播放 24 PAGE.audio.src = voiceSrc; 25 PAGE.audio.play(); 26 PAGE.Event_PlayVoice(); 27 }, false);
每段语音可以暂停、继续播放、重新播放;
这个比较简单,但是也是比较多逻辑。需要变换样式告诉用户,怎样是继续播放/重新播放。
播放中的语音有动画,不是播放中的语音则会停止动画。
这里主要是CSS3动画的应用
1 .app-voice-pause,.app-voice-play{ 2 height: 18px; 3 background-repeat: no-repeat; 4 background-image: url(../img/voice.png); 5 background-size: 18px auto; 6 opacity: 0.5; 7 } 8 .app-voice-you .app-voice-pause{ 9 /*从未播放*/ 10 background-position: 0px -39px; 11 } 12 .app-voice-you .app-voice-play{ 13 /*播放中(不需要过渡动画)*/ 14 background-position: 0px -39px; 15 -webkit-animation: voiceplay 1s infinite step-start; 16 -moz-animation: voiceplay 1s infinite step-start; 17 -o-animation: voiceplay 1s infinite step-start; 18 animation: voiceplay 1s infinite step-start; 19 } 20 @-webkit-keyframes voiceplay { 21 0%, 22 100% { 23 background-position: 0px -39px; 24 } 25 33.333333% { 26 background-position: 0px -0px; 27 } 28 66.666666% { 29 background-position: 0px -19.7px; 30 } 31 }