mirror of
https://github.com/vsariola/sointu.git
synced 2025-05-28 03:10:24 -04:00
add wasm instantiation example
This commit is contained in:
parent
6d4529971c
commit
92c1fdc2d7
BIN
examples/.DS_Store
vendored
Normal file
BIN
examples/.DS_Store
vendored
Normal file
Binary file not shown.
BIN
examples/code/.DS_Store
vendored
Normal file
BIN
examples/code/.DS_Store
vendored
Normal file
Binary file not shown.
14
examples/code/wasm/README.md
Normal file
14
examples/code/wasm/README.md
Normal file
@ -0,0 +1,14 @@
|
||||
Requirements: sointu binaries, `wabt`
|
||||
|
||||
To generate the .wasm file:
|
||||
|
||||
```
|
||||
sointu-compile -o . -arch=wasm tests/test_chords.yml
|
||||
wat2wasm --enable-bulk-memory test_chords.wat
|
||||
```
|
||||
|
||||
To run the example:
|
||||
|
||||
```
|
||||
npx serve examples/code/wasm
|
||||
```
|
57
examples/code/wasm/index.html
Normal file
57
examples/code/wasm/index.html
Normal file
@ -0,0 +1,57 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>sointu WASM example</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<script type="module">
|
||||
// button to start audio context
|
||||
const button = document.createElement("button");
|
||||
button.innerHTML = "start";
|
||||
document.body.appendChild(button);
|
||||
button.onclick = () => {
|
||||
document.body.removeChild(button);
|
||||
|
||||
fetch("test_chords.wasm")
|
||||
.then((response) => response.arrayBuffer())
|
||||
.then((bytes) => WebAssembly.instantiate(bytes, { m: Math }))
|
||||
.then(({ instance }) => {
|
||||
const context = new AudioContext();
|
||||
|
||||
let wasmBuffer = instance.exports.t.value
|
||||
? new Int16Array(
|
||||
instance.exports.m.buffer,
|
||||
instance.exports.s.value,
|
||||
instance.exports.l.value / 2
|
||||
)
|
||||
: new Float32Array(
|
||||
instance.exports.m.buffer,
|
||||
instance.exports.s.value,
|
||||
instance.exports.l.value / 4
|
||||
);
|
||||
|
||||
const buffer = context.createBuffer(
|
||||
2,
|
||||
context.sampleRate * 2,
|
||||
context.sampleRate
|
||||
);
|
||||
|
||||
// convert wasm buffer to audio buffer
|
||||
for (let channel = 0; channel < 2; channel++) {
|
||||
const buffering = buffer.getChannelData(channel);
|
||||
for (let i = 0; i < context.sampleRate * 2; i++) {
|
||||
buffering[i] = wasmBuffer[i];
|
||||
}
|
||||
}
|
||||
|
||||
// connect to output and start playing
|
||||
const src = context.createBufferSource();
|
||||
src.buffer = buffer;
|
||||
src.connect(context.destination);
|
||||
src.start();
|
||||
});
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
BIN
examples/code/wasm/test_chords.wasm
Normal file
BIN
examples/code/wasm/test_chords.wasm
Normal file
Binary file not shown.
Loading…
Reference in New Issue
Block a user