最近看到有一個叫做“輕客小伙伴”的微信服務號,運營得挺不錯的。
它是做英語線上培訓的,由老師錄制語音,配上圖文,制作成課程。

花了不少時間寫了大多數功能,但還沒有優化成插件,直接發代碼估計也看不懂,難應用。所以就主要說下實現的思路。
我的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是點擊的語音的documentvar 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; }}以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答