-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvgmplay-audio-processor.js
More file actions
91 lines (78 loc) · 2.5 KB
/
Copy pathvgmplay-audio-processor.js
File metadata and controls
91 lines (78 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* AudioWorklet processor for VGMPlay-js
* Receives pre-generated audio buffers from the main thread via postMessage
* and outputs them in the process() callback.
*/
class VGMPlayProcessor extends AudioWorkletProcessor {
constructor() {
super();
// Ring buffer: array of {left: Float32Array, right: Float32Array}
this.queue = [];
this.currentChunk = null;
this.currentOffset = 0;
this.playing = false;
this.port.onmessage = (e) => {
const msg = e.data;
if (msg.type === 'buffer') {
this.queue.push({ left: msg.left, right: msg.right });
} else if (msg.type === 'start') {
this.playing = true;
} else if (msg.type === 'pause') {
this.playing = false;
} else if (msg.type === 'stop') {
this.playing = false;
this.queue = [];
this.currentChunk = null;
this.currentOffset = 0;
}
};
}
process(inputs, outputs, parameters) {
const output = outputs[0];
if (!output || output.length < 2) return true;
const outLeft = output[0];
const outRight = output[1];
const frameCount = outLeft.length; // typically 128
if (!this.playing) {
// Output silence
outLeft.fill(0);
outRight.fill(0);
return true;
}
let written = 0;
while (written < frameCount) {
// Get a chunk if we don't have one
if (!this.currentChunk) {
if (this.queue.length === 0) {
// Underrun — fill remainder with silence
outLeft.fill(0, written);
outRight.fill(0, written);
break;
}
this.currentChunk = this.queue.shift();
this.currentOffset = 0;
}
const chunkLeft = this.currentChunk.left;
const chunkRight = this.currentChunk.right;
const available = chunkLeft.length - this.currentOffset;
const needed = frameCount - written;
const toCopy = Math.min(available, needed);
for (let i = 0; i < toCopy; i++) {
outLeft[written + i] = chunkLeft[this.currentOffset + i];
outRight[written + i] = chunkRight[this.currentOffset + i];
}
written += toCopy;
this.currentOffset += toCopy;
if (this.currentOffset >= chunkLeft.length) {
this.currentChunk = null;
this.currentOffset = 0;
}
}
// Request more data when queue is getting low
if (this.queue.length < 6) {
this.port.postMessage({ type: 'need-data' });
}
return true;
}
}
registerProcessor('vgmplay-processor', VGMPlayProcessor);