Posted on

Web Workers and the DOM

Web workers do not have access to the following JavaScript objects:

  • The window object
  • The document object
  • The parent object

main.js runs in the main UI thread

var worker = new Worker("worker.js")
woker.onmessage = function(event) {
    document.getElementById("result").innerHTML = event.data
}
// Post message to the worker
worker.postMessage({"cmd": "start", "msg": "Hello"}) 

worker.js runs in a separate thread

self.onmessage = function(event) {
    var data = event.data
    self.postMessage(data.cmd + " " + data.msg)
}

Note: There are two ways to stop a worker: by calling worker.terminate() from the main UI thread or by calling self.close() inside of the worker thread.

Use Transferable objects to efficiently pass binary data between main and worker thread without copying the data. The usual FileBlobArrayBuffer, and JSON objects will be copied between main thread and worker thread, making them more resource expensive.

Posted on

AudioBuffer Timing Precision

It can anywhere between 100ms and 20 micro seconds.

It all depends on the browser.

AudioContext.currentTime returns a double representing an ever-increasing hardware timestamp in seconds with a certain precision that can be used for scheduling audio playback, visualizing timelines, etc.

AudioBuffer can be started at the particular time.

AudioBufferSourceNode.start([when][, offset][, duration])

For one example, a seamless two-buffer playback.

AudioBuffer0.start()
AudioBuffer1.start(AudioBuffer0.buffer.duration)

AudioBuffer1 will start when AudioBuffer0 is done. Hopfully, this will play continuously without hick-up between buffer0 to buffer1 transition. And when AudioBuffer0.onended event fires, queue another AudioBuffer0 with the start time set to the end time of AudioBuffer1. At AudioBuffer1.onended event, queue another AudioBuffer1 with start time of the end of AudioBuffer0. By switching between these two buffers, it should play smoothly and continuously as if it is one longer buffer.

Not sure if this really will work as expected. To be determined later by actually coding to this spec.

The real test result: there are audible hick-ups. It does not work. :-0

createScriptProcessor is last hope.