JavaScriptで音楽データを再生・操作する

....

/

view source

JavaScript

// JavaScriptで音楽プレイヤー風のUIを表現する

var files = [
  'g.mp3',
];
var eles = [];
const eleIds = [
  'player',
  'files',
  'input',
  'tip',
  'seek',
  'time',
  'player',
  'currentTime',
  'duration',
  'play',
  'pause',
  'stop',
  'volume',
];
eleIds.forEach(function(id){
  eles[id]  = document.getElementById(id);
});


var readyFiles = function(){
  eles['files'].innerHTML = '';
  files.forEach(function(fileName){
    let li = document.createElement('li');
    li.textContent = fileName;
    eles['files'].appendChild(li);
  });

  audio.addEventListener('loadedmetadata', function(e) {
    audio.volume = Number(eles['volume'].value)/100;
    eles['currentTime'].textContent = hhmmss(0);
    eles['duration'].textContent = hhmmss(audio.duration);


    var id3v1 = (new Uint8Array(e.target.result)).slice(-128);
    var judge = id3v1[0] + id3v1[1] + id3v1[2];
    if (judge == 220) {
      for (var i = 3; i < 93; i++) {
         //if (i == 33 || i == 63) trackInfo.innerHTML += '<br>';
         console.log(String.fromCharCode(id3v1[i]));
      }
    }

    setInterval(function(){
      if(audio.duration ===0 && audio.paused){return;}
      eles['seek'].value = audio.currentTime/audio.duration * 100;
      eles['currentTime'].textContent = hhmmss(audio.currentTime);
    }, 999);
  });
}


var hhmmss = function(time){
  time = Math.floor(time);
  let h = Math.floor(time / (60*60));
  let m = Math.floor((time-h*60*60) / (60));
  let s = Math.floor((time-m*60) / (1));
  [h,m,s] = [h,m,s].map(v => ('00' + v).slice(-2));
  return [h,m,s].join(':');
}


eles['play'].addEventListener('click', function(){
  audio.play();
  return false;
});
eles['pause'].addEventListener('click', function(){
  audio.pause();
  return false;
});
eles['stop'].addEventListener('click', function(){
  audio.currentTime = 0;
  audio.pause();
  return false;
});


eles['volume'].addEventListener('input', function(e) {
  audio.volume = Number(e.target.value)/100;
  eles['tip'].style.display = 'inline-block';
  eles['tip'].textContent = e.target.value;
});
eles['seek'].addEventListener('input', function(e) {
  audio.currentTime = Number(e.target.value)*audio.duration/100;
  eles['tip'].style.display = 'inline-block';
  eles['tip'].textContent = hhmmss(audio.currentTime);
});

eles['volume'].addEventListener('mousemove', function(e){
  eles['tip'].style.left = (e.pageX-10) + 'px';
  eles['tip'].style.top = (e.target.getBoundingClientRect().top-22) + 'px';
});
eles['volume'].addEventListener('mouseup', function(e){
  eles['tip'].style.display = 'none';
  eles['tip'].textContent = '';
});

eles['seek'].addEventListener('mousemove', function(e){
  eles['tip'].style.left = (e.pageX-10) + 'px';
  eles['tip'].style.top = (e.target.getBoundingClientRect().top-22) + 'px';
});
eles['seek'].addEventListener('mouseup', function(e){
  eles['tip'].style.display = 'none';
  eles['tip'].textContent = '';
});




var audio = new Audio(files[0]);
readyFiles();






eles['input'].onchange = function() {
  let file = this.files[0];
  let reader = new FileReader();
  files = [
    file.name,
  ];
  reader.readAsDataURL(file)
  reader.onload = function(e){
    audio.pause();
    audio = new Audio(reader.result);
    readyFiles();
    audio.play();

  }
}


var  dragArea = document.body;
dragArea.ondragstart = function(event){
  if(!event.dataTranfer){return;}
  event.dataTranfer.addElement(container);
}
dragArea.ondragover = function(event){
  event.preventDefault();
}
dragArea.ondragleave = function(event){
  event.preventDefault();
}
dragArea.ondrop = function(event){
  event.preventDefault();
  if(!event.dataTransfer.files.length){return;}
  var file = event.dataTransfer.files[0];
  var reader = new FileReader();
  files = [
    file.name,
  ];
  reader.readAsDataURL(file)
  reader.onload = function(){
    audio.pause();
    audio = new Audio(reader.result);
    readyFiles();
    audio.play();
  }
}

CSS

#demo *{
  box-sizing:border-box;
  user-select:none;
}


#demo{
}

#playerWrap{
  display:flex;
  min-height:400px;
  align-items: center;
  justify-content: center;
}
#player{
  width:320px;
  max-width:100%;
}

#files{
  padding:5px;
}
#files li{
  text-overflow:ellipsis;
}

input[type="file"]{
  display:none;
}
input[type="range"]{
  -webkit-appearance: none;
  appearance: none;
  display:block;
  cursor:pointer;
}
 
input[type="range"]:focus,
input[type="range"]:active {
  outline: none;
}
 
input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  cursor: pointer;
  position: relative;
  border: none;
  width: 1px;
  height: 20px;
  display: block;
  background-color: #666;
}


#seek{
  width:100%;
  background-color: #eee;
}
.buttons{
  display:flex;
}

#player ul{
}

#player .buttons li{
  width:40px;
  height:40px;
}

#player .buttons a{
  display:block;
  width:100%;
  height:100%;
  padding:5px;
}

#player .buttons a:hover{
  background-color:rgba(0,0,0,.1);
}
#volume{
  width:80px;
  height:20px;
  margin-top:20px;
  background:linear-gradient(to bottom right, transparent 50%, #eee 50% , #eee)
}

#volume::-webkit-slider-thumb{
  background-color: #888;
}

#tip{
  position:absolute;
  left:0;
  top:0;
  z-index:9;
  padding:2px;
  background-color:#ffe;
  border:1px solid rgba(0,0,0,.5);
  display:none;
  font-size:12px;
}

HTML

ページのソースを表示 : Ctrl+U , DevTools : F12

view-source:https://hi0a.com/demo/-js/js-audio/

ABOUT

hi0a.com 「ひまアプリ」は無料で遊べるミニゲームや便利ツールを公開しています。

プログラミング言語の動作デモやWEBデザイン、ソースコード、フロントエンド等の開発者のための技術を公開しています。

必要な機能の関数をコピペ利用したり勉強に活用できます。

プログラムの動作サンプル結果は画面上部に出力表示されています。

環境:最新のブラウザ GoogleChrome / Windows / Android / iPhone 等の端末で動作確認しています。

画像素材や音素材は半分自作でフリー素材配布サイトも利用しています。LINK参照。

動く便利なものが好きなだけで技術自体に興味はないのでコードは汚いです。

途中放置や実験状態、仕様変更、API廃止等で動かないページもあります。