I am trying to use new AudioContext(). audioWorklet.addModule(URL.createObjectURL(blob))
Load, but the console prompts error: cross source, if it is file://
protocol, how to use audioWorklet
?
I tried to use new Blob([Source Code], {type: 'application/javascript'});
, but still prompted an error
However, the
file://
protocolnew Worker(URL.createObjectURL(blob))
method can be used in Chrome.
const getMp3=()=>{
// return arrayBuffer
};
const playWorkletStr = async () => {
let audioContext = new AudioContext();
let audioBuffer = await audioContext.decodeAudioData(getMp3());
let bypass = `class Bypass extends AudioWorkletProcessor {
process(inputs, outputs) {
const input = inputs[0];
const output = outputs[0];
for (let channel = 0; channel < output.length; ++channel) {
output[channel].set(input[channel]);
}
return true;
}
}
registerProcessor('bypass', Bypass);
`;
let blob = new Blob([bypass], {type: 'application/javascript'});
await audioContext.audioWorklet.addModule(URL.createObjectURL(blob));
const bypasser = new AudioWorkletNode(audioContext, 'bypass');
let source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(bypasser).connect(audioContext.destination);
source.start();
};
document.getElementById('btn').onclick = () => {
playWorkletStr();
};
<button id="btn">play</button>
<script src="index.js"></script>