我正在使用 OfflineAudioContext 在后台进行波形分析。
在 Chrome、Firefox 和 Opera 中一切正常,但在 Safari 中我得到了一个非常狡猾的行为。波形应该由许多样本(329)组成,但在 Safari 中,样本只有 ~38。
window.AudioContext = window.AudioContext || window.webkitAudioContext;
window.OfflineAudioContext = window.OfflineAudioContext ||
window.webkitOfflineAudioContext;
const sharedAudioContext = new AudioContext();
const audioURL = 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/1141585/song.mp3';
const audioDidLoad = ( buffer ) =>
{
console.log("audio decoded");
var samplesCount = 0;
const context = new OfflineAudioContext(1, buffer.length, 44100);
const source = context.createBufferSource();
const processor = context.createScriptProcessor(2048, 1, 1);
const analyser = context.createAnalyser();
analyser.fftSize = 2048;
analyser.smoothingTimeConstant = 0.25;
source.buffer = buffer;
source.connect(analyser);
analyser.connect(processor);
processor.connect(context.destination);
var freqData = new Uint8Array(analyser.frequencyBinCount);
processor.onaudioprocess = () =>
{
analyser.getByteFrequencyData(freqData);
samplesCount++;
};
source.start(0);
context.startRendering();
context.oncomplete = (e) => {
document.getElementById('result').innerHTML = 'Read ' + samplesCount + ' samples';
source.disconnect( analyser );
processor.disconnect( context.destination );
};
};
var request = new XMLHttpRequest();
request.open('GET', audioURL, true);
request.responseType = 'arraybuffer';
request.onload = () => {
var audioData = request.response;
sharedAudioContext.decodeAudioData(
audioData,
audioDidLoad,
e => { console.log("Error with decoding audio data" + e.err); }
);
};
request.send();
请参阅Codepen。