audio 音乐播放器

发布于 2021-12-15  252 次阅读


htmlcssjs
 <audio style="height: 0; width: 0; " id="music" src="music/惊雷.mp3"></audio>
 <div class="progress">
     <span class="start"></span>
     <div class="progress-bar">
          <div class="now"></div>
     </div>
     <span class="end"></span>
 </div>
 .progress{
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 5.80rem;
    margin: 0.5rem auto;
}
.progress-bar{
    position: relative;
    width: 70%;
    height: 0.1rem;
    background-color: #eee;
    vertical-align: 2px;
    border-radius: 20px;
    cursor: pointer;
}
.now{
    position: absolute;
    left: 0;
    display: inline-block;
    height: 0.1rem;
    width: 0%;
    background: #31c27c;
}
.now::after{
    content: '';
    position: absolute;
    left: 100%;
    width: 0.05rem;
    height: 0.1rem;
    background-color: lightskyblue;
}
 const audio = document.getElementById('music');
 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 () {
     var end = conversion(audio.duration);
     $('.end').html(end);
     var start = conversion(audio.currentTime);
     $('.start').html(start);
 }

 progressBar.addEventListener('click', function (event) {
     let coordStart = this.getBoundingClientRect().left;
     let coordEnd = event.pageX;
     let p = (coordEnd - coordStart) / this.offsetWidth
     $('.now').css({
         'width': p.toFixed(3) * 100 + "%"
     })
     audio.currentTime = p * audio.duration;
     audio.play();
 })

 setInterval(() => {
     var start = conversion(audio.currentTime);
     $('.start').html(start);
     $('.now').css({
         'width': audio.currentTime / audio.duration.toFixed(3) * 100 -1 + '%'
     });
 }, 1000)

 

 


一沙一世界,一花一天堂。君掌盛无边,刹那成永恒。