--- title: AudioContext.decodeAudioData() slug: Web/API/BaseAudioContext/decodeAudioData tags: - API - Audio - audio接口 - 音频解码 translation_of: Web/API/BaseAudioContext/decodeAudioData original_slug: Web/API/AudioContext/decodeAudioData ---
{{ APIRef("Web Audio API") }}
{{ domxref("AudioContext") }}接口的decodeAudioData()方法可用于异步解码
音频文件中的 {{domxref("ArrayBuffer")}}. ArrayBuffer数据可以通过
{{domxref("XMLHttpRequest")}}和{{domxref("FileReader")}}来获取. AudioBuffer是通过AudioContext采样率进行解码的,然后通过回调返回结果.
这是从音频轨道创建用于web audio API音频源的首选方法。
旧版的回调函数语法
audioCtx.decodeAudioData(audioData, function(decodedData) { // use the decoded data here });
新版的promise-based语法:
audioCtx.decodeAudioData(audioData).then(function(decodedData) { // use the decoded data here });
在本章节中,我们将首先学习基于回调的系统,然后采用新的基于promise-based的语法
在这个事例中, getData()
方法使用XHR加载一个音轨,设置请求的responsetype为ArrayBuffer使它返回一个arraybuffer数据,然后存储在audioData变量中. 然后我们将这个arraybuffer数据置于decodeAudioData()方法中使用,当成功解码PCM Data后通过回调返回
, 将返回的结果通过{{ domxref("AudioContext.createBufferSource()") }}接口进行处理并获得一个{{ domxref("AudioBufferSourceNode") }}, 将源连接至{{domxref("AudioContext.destination") }}并将它设置为循环的.
通过按钮来运行 getData()
来获取音轨并播放它. 当使用 stop()
方法后source将会被清除.
Note: You can run the example live (or view the source.)
// define variables var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var source; var pre = document.querySelector('pre'); var myScript = document.querySelector('script'); var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); // use XHR to load an audio track, and // decodeAudioData to decode it and stick it in a buffer. // Then we put the buffer into the source function getData() { source = audioCtx.createBufferSource(); var request = new XMLHttpRequest(); request.open('GET', 'viper.ogg', true); request.responseType = 'arraybuffer'; request.onload = function() { var audioData = request.response; audioCtx.decodeAudioData(audioData, function(buffer) { source.buffer = buffer; source.connect(audioCtx.destination); source.loop = true; }, function(e){"Error with decoding audio data" + e.err}); } request.send(); } // wire up buttons to stop and play audio play.onclick = function() { getData(); source.start(0); play.setAttribute('disabled', 'disabled'); } stop.onclick = function() { source.stop(0); play.removeAttribute('disabled'); } // dump script to pre element pre.innerHTML = myScript.innerHTML;
ctx.decodeAudioData(compressedBuffer).then(function(decodedData) { // use the decoded data here });
一个 {{domxref("Promise") }}对象.
Specification | Status | Comment |
---|---|---|
{{SpecName('Web Audio API', '#widl-AudioContext-decodeAudioData-Promise-AudioBuffer--ArrayBuffer-audioData-DecodeSuccessCallback-successCallback-DecodeErrorCallback-errorCallback', 'decodeAudioData()')}} | {{Spec2('Web Audio API')}} |