zig dsp poc

This commit is contained in:
Felix Roos
2024-01-10 18:11:05 +01:00
parent 0106a129c9
commit 93cfe9802c
8 changed files with 61 additions and 16 deletions
+2 -2
View File
@@ -3,8 +3,8 @@
<https://dev.to/sleibrock/webassembly-with-zig-part-1-4onm>
```sh
# (re)compile add.zig
zig build-lib add.zig -target wasm32-freestanding -dynamic -rdynamic
# (re)compile dsp.zig
zig build-lib dsp.zig -target wasm32-freestanding -dynamic -rdynamic
# run server
npx http-server -o
```
Binary file not shown.
-3
View File
@@ -1,3 +0,0 @@
export fn add(a: i32, b: i32) i32 {
return a + b;
}
BIN
View File
Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
const std = @import("std");
export fn saw(t: f64) f64 {
return ((@mod(110.0 * t, 1.0)) - 0.5) * 2.0;
}
+1 -1
View File
@@ -4,7 +4,7 @@
<title>ZIG / WASM Demo</title>
</head>
<body>
<h3>check the console</h3>
<button id="play">play</button>
</body>
<script src="./main.js"></script>
</html>
+16 -10
View File
@@ -1,11 +1,17 @@
async function run() {
let res = await fetch('./add.wasm');
res = await res.arrayBuffer();
res = await WebAssembly.instantiate(res, {
env: {},
});
const { add } = res.instance.exports;
console.log(add(3, 5));
}
let ac;
document.getElementById('play').addEventListener('click', async () => {
ac = ac || new AudioContext();
await ac.resume();
await ac.audioWorklet.addModule('./worklet.js');
const node = new AudioWorkletNode(ac, 'saw-processor');
run();
let res = await fetch('./dsp.wasm');
const buffer = await res.arrayBuffer();
node.port.onmessage = (e) => {
if (e.data === 'OK') {
console.log('worklet ready');
}
};
node.port.postMessage({ webassembly: buffer });
node.connect(ac.destination);
});
+37
View File
@@ -0,0 +1,37 @@
class SawProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.t = 0; // samples passed
this.port.onmessage = (e) => {
const key = Object.keys(e.data)[0];
const value = e.data[key];
switch (key) {
case 'webassembly':
WebAssembly.instantiate(value, this.importObject).then((result) => {
const exports = result.instance.exports;
this.api = result.instance.exports;
this.saw = exports.saw;
this.port.postMessage('OK');
});
break;
}
};
}
process(inputs, outputs, parameters) {
if (this.api) {
const output = outputs[0];
for (let i = 0; i < output[0].length; i++) {
let t = this.t;
let out = 0;
out = this.api.saw(t / 44100, 220);
output.forEach((channel) => {
channel[i] = out;
});
this.t++;
}
}
return true;
}
}
registerProcessor('saw-processor', SawProcessor);