av/cmd/audio-player/main.js

86 lines
2.7 KiB
JavaScript

const go = new Go()
// memoryBytes is an Uint8Array pointing to the webassembly linear memory.
let memoryBytes;
let bytes;
let mod, inst
console.log("Initializing wasm...")
WebAssembly.instantiateStreaming(
fetch('lib.wasm'), go.importObject).then(
result => {
mod = result.module
inst = result.instance
memoryBytes = new Uint8Array(inst.exports.mem.buffer)
console.log("Initialization complete.")
run()
}
)
async function run() {
await go.run(inst)
inst = await WebAssembly.instantiate(mod, go.importObject) // reset instance
}
let memPointer
// gotMem sets the webassembly linear memory with the data buffer result
// at the slice header pointer passed from Go.
function gotMem(pointer) {
memPointer = pointer
memoryBytes.set(bytes, pointer);
// Now the data can be loaded from the slice.
loadData();
}
// // displayImage takes the pointer to the target image in the wasm linear memory
// // and its length. Gets the resulting byte slice and creates an image blob.
// function displayImage(pointer, length) {
// let resultBytes = memoryBytes.slice(pointer, pointer + length);
// let blob = new Blob([resultBytes], {
// 'type': imageType
// });
// document.getElementById('targetImg').src = URL.createObjectURL(blob);
// }
// document.getElementById('input').addEventListener('change', function () {
// let reader = new FileReader();
// reader.onload = (ev) => {
// bytes = new Uint8Array(ev.target.result);
// initMem(bytes.length);
// let blob = new Blob([bytes], {
// 'type': imageType
// });
// document.getElementById("sourceImg").src = URL.createObjectURL(blob);
// };
// imageType = this.files[0].type;
// reader.readAsArrayBuffer(this.files[0]);
// });
window.onload = function () {
document.getElementById('input').addEventListener('change', function () {
const input = event.target.files[0]
const reader = new FileReader()
reader.onload = event => {
bytes = new Uint8Array(event.target.result)
initMem(bytes.length)
let resultBuffer = new ArrayBuffer(getDecLen());
let resultBytes = new Uint8Array(resultBuffer)
resultBytes.set(memoryBytes.slice(memPointer, memPointer + getDecLen()))
console.log("playing file")
var player = new PCMPlayer({
encoding: '16bitInt',
channels: 1,
sampleRate: 48000,
flushingTime: 2000
});
player.feed(resultBytes)
}
reader.onerror = error => reject(error)
reader.readAsArrayBuffer(input)
})
}