我正在尝试从另一个模块更改 AudioWorkletProcessor 使用的值,但从 AudioWorkletProcessor 的上下文来看,该值不会改变并且保持不变。但是从修改数据的模块来看,当查询到数据时,实际上已经发生了变化。就像有一个完全独立的模块实例/状态,它为修饰符(main.js)和读取器(audio-processor.js)保存数据(functions.js)
在这里我们有audio-processor.js
import { sawWave } from "/src/functions.js";
var tick = 0
class AudioProcessor extends AudioWorkletProcessor {
process(inputs, outputs, parameters) {
const output = outputs[0]
output.forEach(channel => {
// emphasis on sawWave function
var value = sawWave(tick) * 0.1;
for (let i = 0; i < channel.length; i++) {
channel[i] = value
}
});
tick++
return true
}
}
registerProcessor('audio-processor', AudioProcessor)
这里我们有functions.js
,它包含被导入到的 sawWave()audio-processor.js
let variables = {
// emphasis on this variable
sawWaveFrequency: 1
}
export function setSawFrequency(freq) {
variables.sawWaveFrequency = freq
}
export function sawWave(tick) {
console.log(variables.sawWaveFrequency)
// this function uses the variable defined above and is imported by audio-processor.js
// variables.sawWaveFrequency doesn't change for audio-processor.js when modified from main.js
// so the output will will always be as if variables.sawWaveFrequency = 1
return tick * variables.sawWaveFrequency % 10;
}
这里我们有main.js
,它处理来自 HTML 页面的输入
import { setSawFrequency } from "/src/functions.js";
var audioContext
var whiteNoiseNode
async function init() {
audioContext = new AudioContext()
await audioContext.audioWorklet.addModule("/src/audio-processor.js")
whiteNoiseNode = new AudioWorkletNode(audioContext, 'audio-processor')
}
function play() {
whiteNoiseNode.connect(audioContext.destination)
}
function main() {
document.querySelector("#play").onclick = play;
document.querySelector("#init").onclick = init;
document.querySelector("#slider-mult").oninput = function() {
// this is supposed to change the value, but only does so in the context of main.js and not audio-processor.js
setSawFrequency(this.value);
}
}
main();
编辑:我认为你只应该使用AudioWorkletProcessor.port
和parameters
过程函数中的参数来与之通信?