由于iOS设备可能具有电源管理功能,可以在后台或屏幕关闭时限制或取消JavaScript执行的优先级(如
this thread
),您可能需要考虑另一种后台任务机制。
尝试
Web API Worker
它将调用您的javascript循环:
<script>
const worker = new Worker('worker.js');
worker.onmessage = function (event) {
// Handle the message from the worker
console.log('Message received from worker:', event.data);
};
</script>
还有你的剧本:
let delay = 10; // milliseconds
function timer() {
let startTime = Date.now();
while (Date.now() < startTime + delay) {}
postMessage({data: []});
setTimeout(timer, delay);
}
timer();
但如果问题仍然存在,那么是的,音频工作者更准确。由于您需要保持交互,请考虑
Audio Worklet API
,用于提供执行的自定义音频处理脚本
在单独的线程中
以提供非常低延迟的音频处理。
作为
documentation suggests
,您需要:
-
扩展
AudioWorkletProcessor
类(请参阅“
Deriving classes
“部分)并提供您自己的
process()
方法;
-
使用注册处理器
AudioWorkletGlobalScope.registerProcessor()
方法
-
使用加载文件
addModule()
方法
audioWorklet
所有物
-
基于处理器创建AudioWorkletNode。处理器将由
AudioWorkletNode
构造函数。
意思是创造
audio-worklet-processor.js
:
class TimerProcessor extends AudioWorkletProcessor {
static get parameterDescriptors() {
return [{ name: 'delay', defaultValue: 10 }];
}
constructor() {
super();
this.timer = 0;
}
process(inputs, outputs, parameters) {
const delay = parameters.delay[0] || 10;
this.timer += 128 / sampleRate * 1000; // 128 is the default buffer size
if (this.timer >= delay) {
this.timer -= delay;
this.port.postMessage({ data: [] });
}
return true; // Keep the processor alive
}
}
registerProcessor('timer-processor', TimerProcessor);
您可以从您的
worker.js
:
(async () => {
// Load the audio worklet processor
const audioContext = new AudioContext();
await audioContext.audioWorklet.addModule('audio-worklet-processor.js');
// Create the audio worklet node and connect it to the destination
const timerNode = new AudioWorkletNode(audioContext, 'timer-processor');
timerNode.connect(audioContext.destination);
// Set up a message listener
timerNode.port.onmessage = (event) => {
// Handle the message from the audio worklet processor
console.log('Message received from audio worklet processor:', event.data);
};
})();
并致电您的员工:
<脚本>
const-worker=新worker('worker.js');
worker.onmessage=函数(事件){
//处理来自工作人员的消息
console.log('从worker接收到的消息:',event.data);
};
</脚本>