由於最近在寫一個音樂播放器,原本想作完整個項目再寫博客的,但抑制不住我體內的洪荒之力,實際上是怕到時候寫起來長,就決定把一些知識點梳理出來css
先了解一下HTML5出的audio標籤html
audio標籤訂義聲音,好比音樂或其餘音頻流瀏覽器
autoplay 若是出現該屬性,則音頻在就緒後立刻播放。oop
controls 若是出現該屬性,則向用戶顯示控件,好比播放按鈕。flex
loop 若是出現該屬性,則每當音頻結束時從新開始播放。ui
preload 若是出現該屬性,則音頻在頁面加載時進行加載,並預備播放。若是使用 "autoplay",則忽略該屬性。this
src 要播放的音頻的 URL。spa
autoplay 設置或返回是否在加載完成後隨即播放音頻/視頻code
controls 設置或返回音頻/視頻是否顯示控件(好比播放/暫停等)視頻
currentSrc 返回當前音頻/視頻的 URL
currentTime 設置或返回音頻/視頻中的當前播放位置(以秒計)
muted 設置或返回音頻/視頻默認是否靜音
duration 返回當前音頻/視頻的長度(以秒計)
ended 返回音頻/視頻的播放是否已結束
paused 設置或返回音頻/視頻是否暫停
played 返回表示音頻/視頻已播放部分的 TimeRanges 對象
load() 從新加載音頻/視頻元素
play() 開始播放音頻/視頻
pause() 暫停當前播放的音頻/視頻
canPlayType() 檢測瀏覽器是否能播放指定的音頻/視頻類型
audio的用法咱們大體上了解了,那麼怎麼製做本身喜歡的進度條呢?
定製本身喜歡的進度條,咱們須要如下步驟:
<audio height="0" width="0" id="music" src="http://dl.stream.qqmusic.qq.com/C400003RCA7t0y6du5.m4a?vkey=6853C20C7E3DAA08D9D79173735CFB95EDF5E926D72FE3BA53CECCC48947127857C41890640C1AE69AAB050AA9B8874767A48AF5BF9066A0&guid=7984684460&uin=0&fromtag=66"></audio>
<div class="progress"> <span class="start"></span> <div class="progress-bar"> <div class="now"></div> </div> <span class="end"></span> </div>
* { margin: 0; padding: 0; } .progress { display: flex; justify-content: space-between; align-items: center; width: 380px; margin: 100px auto; } .progress-bar { position: relative; width: 70%; height: 5px; background-color: #eee; vertical-align: 2px; border-radius: 3px; cursor: pointer; } .now { position: absolute; left: 0; display: inline-block; height: 5px; width: 70%; background: #31c27c; } .now::after { content: ''; position: absolute; left: 100%; width: 3px; height: 7px; background-color: lightblue; }
const audio = document.getElementById('music') const start = document.querySelector('.start') const end = document.querySelector('.end') const progressBar = document.querySelector('.progress-bar') const now = document.querySelector('.now') function conversion (value) { let minute = Math.floor(value / 60) minute = minute.toString().length === 1 ? ('0' + minute) : minute let second = Math.round(value % 60) second = second.toString().length === 1 ? ('0' + second) : second return `${minute}:${second}` } audio.onloadedmetadata = function () { end.innerHTML = conversion(audio.duration) start.innerHTML = conversion(audio.currentTime) } progressBar.addEventListener('click', function (event) { let coordStart = this.getBoundingClientRect().left let coordEnd = event.pageX let p = (coordEnd - coordStart) / this.offsetWidth now.style.width = p.toFixed(3) * 100 + '%' audio.currentTime = p * audio.duration audio.play() }) setInterval(() => { start.innerHTML = conversion(audio.currentTime) now.style.width = audio.currentTime / audio.duration.toFixed(3) * 100 + '%' }, 1000)
到這裏進度條就完成了~~