Collect from 網頁模板
Modified by 追夢人物的博客

Web Audio Api實作紀要(一)

利用HTML5 AUDIO TAG自動連續播放音樂

  近來因為web 技術的蓬勃發展,在網頁裡播放音樂已經可以不需要透過 flash 或 quicktime 等外掛程式輔助,只要使用 HTML5 的 audio tag 就可以播放音樂,利用W3C 所規範的 Web Audio API 就可以做許多進階的聲音控制和應用,我在搜尋學習過程中發現很多很棒的資料與網頁,它們分散各處,在這裡特別紀錄一下並將我修改實作的內容紀錄一下,以防遺忘,如果資料或說法有誤,歡迎指教。

  控制HTML5 的 audio tag很容易,一般會透過JavaScript或jquery程式碼來控制,找到的資料有很多種方法,因為對這些語言也不十分熟悉,整合起來也遇到一些狀況,但實作起來結果是可行的。博客右下方有一個撥放本地MP3的功能,程式碼如下: HTML5 CODE

<input type="file" id="input" multiple="true" >
<audio  id="myAudio" autoplay preload="auto" onended="myFunction()" controls></audio>

JavaScript Code 取得多個本地音樂檔加入陣列中,撥放完一首觸發myFunction(),並將陣列最後一個元素刪除,最後一首播完後解除綁定

var $audio = $('#myAudio');
$('input').on('change', function(e) {
  var target = e.currentTarget; 
  arr = [];  
  var files = $(this)[0].files;
//將選取檔案加入arr陣列中  
     for ( var i = 0; i < files.length ; i++) {
        file = target.files[i];
        arr.push(URL.createObjectURL(file));
        console.log(arr[i]);
     }  
   if (target.files && file) {
        var reader = new FileReader();
        reader.onload = function (e) {
        $audio.attr('src', e.target.result);            
        }
        arr.pop();
        reader.readAsDataURL(file);                          
    }

});

//播放結束觸發函數  
function myFunction(){
document.getElementById("myAudio").src = arr.pop();
!arr.length && myAudio.removeEventListener('ended',myFunction,false);//只有一个元素时解除绑定
};

加入頻譜圖

//HTML5 CODE
<div id="d"><div style="height: 0px;"></div><div style="height: 0px;"></div>

//JaveScript  CODE
 var s = document.getElementById('s');
  var d = document.getElementById('d');
  for(var i=0; i<128; i++){
    d.innerHTML += '<div></div>';
  }
  var dd = document.querySelectorAll('#d div');
  //var audioCtx = new(window.AudioContext || window.webkitAudioContext)();
  var audioCtx = new AudioContext();
  var myAudio = document.querySelector('audio');
  var source = audioCtx.createMediaElementSource(myAudio);
  var gainNode = audioCtx.createGain();
  var processor = audioCtx.createScriptProcessor(4096, 1, 1);
  source.connect(processor);
  gainNode.connect(processor);
  processor.connect(audioCtx.destination);

  processor.onaudioprocess = function(e) {
    var input = e.inputBuffer.getChannelData(0);
    var output = e.outputBuffer.getChannelData(0);
    for (var i = 0; i < input.length; i++) {
      output[i] = input[i];
    }
    //console.log(output);
    for(var j=0; j<128; j++){
      dd[j].style.height = output[j*32]*100+'px';
    }
  };

可以一次選多個檔案,會自動從最後一首依次往前自動撥放 新版的Chrome有自動靜音的機制,所以有些範例在本機上實作時需要加入啟動靜音,下方程式碼會在網頁右下角產生unmute按鈕,解開這個限制。

<script>
/**
 * Copyright 2018 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 //手動關閉靜音模式
(function () {
  const list = []; 
  self.AudioContext = new Proxy(self.AudioContext, {
    construct(target, args) {
      const result =  new target(...args);
      list.push(result);
      return result;
    }   
  }); 

  const btn = document.createElement('button');
  btn.classList.add('unmute');
  btn.style.position = 'fixed';
  btn.style.bottom = '0';
  btn.style.right = '0';
  btn.textContent = '🔇 unmute';
  btn.style.fontSize = '1em';
  btn.onclick = e => {
    list.forEach(ctx => ctx.resume());
    btn.remove();
  };  
  document.addEventListener('DOMContentLoaded', _ => {
    document.body.appendChild(btn);
  }); 
})();
</script>

發表評論

評論列表,共 0 則評論

    暫無評論