HTML5 WebAudioAPI簡介(一)


一、常用對象

1.AudioContext對象

AudioContext是一個專門用於音頻處理的接口,並且原理是講AudioContext創建出來的各種節點(AudioNode)相互連接,音頻數據流經這些節點並作出相應處理。

創建AudioContent對象

//普通寫法
var audioContext=new window.AudioContext();
//為了兼容,也可以這樣寫
window.AudioContext = window.AudioContext || window.webkitAudioContext || 
window.mozAudioContext || window.msAudioContext; //也可以使用錯誤處理 try { var audioContext = new window.AudioContext(); } catch (e) { Console.log('!Your browser does not support AudioContext'); }

解碼音頻文件

audioContext.decodeAudioData(binary, function(buffer) { ... });

讀取到的音頻文件時2進制文件(可以使用Ajax遠程加載,可以使用FileAPI讀取本地文件),

我們需要讓AudioContext先對其解碼,然后再進行后續擦做。

返回結果的buffer為AudioBuffer類型數據。

2.AudioBuffer對象

length:文件大小

duration:音頻長度

3.創建音頻處理節點

AudioBufferSourceNode對象

//創建AudioBufferSourceNode對象
var source = ctx.createBufferSource();

鏈接節點:

                    //創建AudioBufferSourceNode對象
                    var source = ctx.createBufferSource();
                    source.buffer = buffer;
                    source.connect(ctx.destination);

AnalyserNode對象(分析器)

創建鏈接點:

//創建分析器
var analyser = ctx.createAnalyser();
source = ctx.createBufferSource();
//將source與分析器鏈接
source.connect(analyser);
//將分析器與destination鏈接,這樣才能形成到達揚聲器的通路
analyser.connect(ctx.destination);
//將解碼后的buffer數據復制給source
source.buffer = buffer;

播放/暫停

audioBufferSourceNode.buffer = buffer; //回調函數傳入的參數 
audioBufferSourceNode.start(0); //指定位置開始播放
audioBufferSourceNode.stop();

 更多參考(中文版):https://developer.mozilla.org/zh-CN/docs/Web/API/AudioContext

更多參考:https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM