オリジナルJS実現音楽プレーヤーのコード例


本論文では、生JSの音楽プレーヤー実現のための例示的なコードを紹介します。
効果図

音楽プレーヤー
  • 再生制御
  • プログレスバー制御
  • を再生する。
  • 歌詞表示とハイライト
  • 再生モード設定
  • プレイヤーのプロパティ
    プレーヤーの機能によって、プレーヤーの属性とDOM元素を分類して、同じ機能を実現する要素と属性は同じオブジェクトに保存して、管理と操作に便利です。
    
    const control = { //       
      play: document.querySelector('#myplay'),
     ...
      index: 2,//        
     ...
    }
    
    const audioFile = { //           
      file: document.getElementsByTagName('audio')[0],
      currentTime: 0,
      duration: 0,
    }
    
    const lyric = { //        
      ele: null,
      totalLyricRows: 0,
      currentRows: 0,
      rowsHeight: 0,
    }
    
    const modeControl = { //    
      mode: ['  ', '  ', '  '],
      index: 0
    }
    
    const songInfo = { //        DOM  
      name: document.querySelector('.song-name'),
     ...
    }
    
    
    コントロール
    機能:音楽の再生と一時停止を制御し、前の曲、次の曲、再生完了及び対応するアイコンの修正
    audio用API:audio.play()とaudio.pause()とaudio endedイベント
    
    //         ,   ,     
    control.play.addEventListener('click',()=>{
      control.isPlay = !control.isPlay;
      playerHandle();
    } );
    control.prev.addEventListener('click', prevHandle);
    control.next.addEventListener('click', nextHandle);
    audioFile.file.addEventListener('ended', nextHandle);
    
    function playerHandle() {
      const play = control.play;
      control.isPlay ? audioFile.file.play() : audioFile.file.pause();
      if (control.isPlay) {
     //    ,           
        play.classList.remove('songStop');
        play.classList.add('songStart');
        control.albumCover.classList.add('albumRotate');
        control.albumCover.style.animationPlayState = 'running';
      } else {
        //    ,           
     ...
      }
    }
    
    
    function prevHandle() {  //             
      const modeIndex = modeControl.index;
      const songListLens = songList.length;
      if (modeIndex == 0) {//    
        let index = --control.index;
        index == -1 ? (index = songListLens - 1) : index;
        control.index = index % songListLens;
      } else if (modeIndex == 1) {//    
        const randomNum = Math.random() * (songListLens - 1);
        control.index = Math.round(randomNum);
      } else if (modeIndex == 2) {//  
      }
      reload(songList);
    }
    
    function nextHandle() {
      const modeIndex = modeControl.index;
      const songListLens = songList.length;
      if (modeIndex == 0) {//    
        control.index = ++control.index % songListLens;
      } else if (modeIndex == 1) {//    
        const randomNum = Math.random() * (songListLens - 1);
        control.index = Math.round(randomNum);
      } else if (modeIndex == 2) {//  
      }
      reload(songList);
    }
    
    
    プレイスケジュールバー制御
    機能:リアルタイムで再生進捗を更新し、進捗バーをクリックして曲の再生進捗を調整する。
    audio用API:audio timeudate事件、audio.currentTime
    
    //         
    audioFile.file.addEventListener('timeupdate', lyricAndProgressMove);
    //         
    control.progressDot.addEventListener('click', adjustProgressByDrag);
    //         
    control.progressWrap.addEventListener('click', adjustProgressByClick);
    
    プレイスケジュールはリアルタイムで更新されます。対応するDOM要素の位置や幅を変更して変更します。
    
    function lyricAndProgressMove() {
      const audio = audioFile.file;
      const controlIndex = control.index;
     //        
      const songLyricItem = document.getElementsByClassName('song-lyric-item');
      if (songLyricItem.length == 0) return;
      let currentTime = audioFile.currentTime = Math.round(audio.currentTime);
      let duration = audioFile.duration = Math.round(audio.duration);
    
      //     
      const progressWrapWidth = control.progressWrap.offsetWidth;
      const currentBarPOS = currentTime / duration * 100;
      control.progressBar.style.width = `${currentBarPOS.toFixed(2)}%`;
      const currentDotPOS = Math.round(currentTime / duration * progressWrapWidth);
      control.progressDot.style.left = `${currentDotPOS}px`;
    
      songInfo.currentTimeSpan.innerText = formatTime(currentTime);
    
    }
    
    
    ドラッグして進捗を調整します。進捗バーをドラッグして移動し、同時に曲の再生進捗を更新します。
    
    function adjustProgressByDrag() {
      const fragBox = control.progressDot;
      const progressWrap = control.progressWrap
      drag(fragBox, progressWrap)
    }
    
    function drag(fragBox, wrap) {
      const wrapWidth = wrap.offsetWidth;
      const wrapLeft = getOffsetLeft(wrap);
    
      function dragMove(e) {
        let disX = e.pageX - wrapLeft;
        changeProgressBarPos(disX, wrapWidth)
      }
      fragBox.addEventListener('mousedown', () => { //    
        //        
        fragBox.style.width = `14px`;fragBox.style.height = `14px`;fragBox.style.top = `-7px`;
        document.addEventListener('mousemove', dragMove);
        document.addEventListener('mouseup', () => {
          document.removeEventListener('mousemove', dragMove);
          fragBox.style.width = `10px`;fragBox.style.height = `10px`;fragBox.style.top = `-4px`;
        })
      });
    }
    
    function changeProgressBarPos(disX, wrapWidth) { //       
      const audio = audioFile.file
      const duration = audioFile.duration
      let dotPos
      let barPos
    
      if (disX < 0) {
        dotPos = -4
        barPos = 0
        audio.currentTime = 0
      } else if (disX > 0 && disX < wrapWidth) {
        dotPos = disX
        barPos = 100 * (disX / wrapWidth)
        audio.currentTime = duration * (disX / wrapWidth)
      } else {
        dotPos = wrapWidth - 4
        barPos = 100
        audio.currentTime = duration
      }
      control.progressDot.style.left = `${dotPos}px`
      control.progressBar.style.width = `${barPos}%`
    }
    
    
    プログレスバーをクリックして調整します。プログレスバーをクリックして、同時に曲の再生進捗を更新します。
    
    function adjustProgressByClick(e) {
    
      const wrap = control.progressWrap;
      const wrapWidth = wrap.offsetWidth;
      const wrapLeft = getOffsetLeft(wrap);
      const disX = e.pageX - wrapLeft;
      changeProgressBarPos(disX, wrapWidth)
    }
    
    
    歌詞の表示とハイライト
    機能:再生の進捗に応じて、歌詞の表示をリアルタイムに更新し、現在の歌詞をハイライトします。
    audio用API:audio timeudate事件、audio.currentTime
    
    //         
    audioFile.file.addEventListener('timeupdate', lyricAndProgressMove);
    
    function lyricAndProgressMove() {
      const audio = audioFile.file;
      const controlIndex = control.index;
    
      const songLyricItem = document.getElementsByClassName('song-lyric-item');
      if (songLyricItem.length == 0) return;
      let currentTime = audioFile.currentTime = Math.round(audio.currentTime);
      let duration = audioFile.duration = Math.round(audio.duration);
      let totalLyricRows = lyric.totalLyricRows = songLyricItem.length;
      let LyricEle = lyric.ele = songLyricItem[0];
      let rowsHeight = lyric.rowsHeight = LyricEle && LyricEle.offsetHeight;
      //    
      lrcs[controlIndex].lyric.forEach((item, index) => {
        if (currentTime === item.time) {
          lyric.currentRows = index;
          songLyricItem[index].classList.add('song-lyric-item-active');
          index > 0 && songLyricItem[index - 1].classList.remove('song-lyric-item-active');
          if (index > 5 && index < totalLyricRows - 5) {
            songInfo.lyricWrap.scrollTo(0, `${rowsHeight * (index - 5)}`)
          }
    
        }
      })
    }
    
    
    プレイモード設定
    機能:ジャンププレイモードをクリックし、対応するアイコンを変更します。
    audioが使っているAPI:なし
    
    //       
    control.mode.addEventListener('click', changePlayMode);
    
    function changePlayMode() {
      modeControl.index = ++modeControl.index % 3;
      const mode = control.mode;
      modeControl.index === 0 ?
        mode.setAttribute("class", "playerIcon songCycleOrder") :
        modeControl.index === 1 ?
          mode.setAttribute("class", "playerIcon songCycleRandom ") :
          mode.setAttribute("class", "playerIcon songCycleOnly")
    }
    
    
    プロジェクトのプレビュー
    コードアドレス:https://github.com/hcm083214/audio-player
    ここでは、生JSの音楽プレーヤー実現のためのコード例についての記事を紹介します。JSの音楽プレーヤーの内容については、以前の記事を検索したり、下記の関連記事を見たりしてください。これからもよろしくお願いします。