@vim3d/threejs 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -0
- package/audio.d.ts +84 -0
- package/audio.js +453 -0
- package/esm/audio.js +449 -0
- package/esm/geometry.js +74 -1
- package/esm/index.js +2 -1
- package/esm/player.js +23 -1
- package/esm/scene.js +21 -10
- package/geometry.d.ts +3 -1
- package/geometry.js +75 -0
- package/index.d.ts +4 -2
- package/index.js +7 -3
- package/package.json +2 -2
- package/player.d.ts +9 -2
- package/player.js +23 -1
- package/scene.js +20 -9
package/README.md
CHANGED
|
@@ -31,6 +31,15 @@ enabled. Loops require a configured frame count. `setFps` changes playback
|
|
|
31
31
|
speed only, not the scene's evaluation clock. Use `onFrame` and
|
|
32
32
|
`onDiagnostics` to observe playback.
|
|
33
33
|
|
|
34
|
+
For live Web Audio channels, create a `WebAudioChannelSource` from an audio
|
|
35
|
+
file (`fromFile`, `fromAudioBuffer`, `fromMediaElement`) or microphone
|
|
36
|
+
(`fromMicrophone`, `fromMediaStream`), declare its `ports` in
|
|
37
|
+
`compileScene(..., { liveChannels: { music: audio.ports } })`, and pass
|
|
38
|
+
`liveChannels: { music: audio }` to `Vim3DPlayer` (or `setLiveChannel`).
|
|
39
|
+
It feeds `loudness`, `bass`, `mid`, `treble`, `onset`, and `travel` (plus
|
|
40
|
+
optional custom frequency bands) into `/ch/<name>/*`, and can record them
|
|
41
|
+
to a Spec 2 Tier-1 JSON channel table with `toChannelTable()`.
|
|
42
|
+
|
|
34
43
|
If you already have a snapshot, use `Vim3DThreeScene.applyFrameSnapshot` and
|
|
35
44
|
render its `scene` yourself. Cameras use the snapshot's evaluated position,
|
|
36
45
|
direction, and up to form a rigid view without rig scale or shear.
|
package/audio.d.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { LiveChannelSample } from '@vim3d/core';
|
|
2
|
+
export declare const DEFAULT_AUDIO_BANDS: Readonly<Record<'bass' | 'mid' | 'treble', readonly [number, number]>>;
|
|
3
|
+
export declare const DEFAULT_AUDIO_FEATURE_PORTS: readonly ["loudness", "bass", "mid", "treble", "onset", "travel"];
|
|
4
|
+
export interface AnalyserLike {
|
|
5
|
+
readonly fftSize: number;
|
|
6
|
+
readonly frequencyBinCount: number;
|
|
7
|
+
readonly context?: {
|
|
8
|
+
readonly sampleRate: number;
|
|
9
|
+
readonly currentTime: number;
|
|
10
|
+
};
|
|
11
|
+
getByteFrequencyData(array: Uint8Array<ArrayBuffer>): void;
|
|
12
|
+
getByteTimeDomainData?(array: Uint8Array<ArrayBuffer>): void;
|
|
13
|
+
getFloatTimeDomainData?(array: Float32Array<ArrayBuffer>): void;
|
|
14
|
+
}
|
|
15
|
+
export interface RecordedChannelTable {
|
|
16
|
+
readonly sampleRate: number;
|
|
17
|
+
readonly boundary: 'clamp' | 'wrap';
|
|
18
|
+
readonly interpolation: 'step' | 'linear';
|
|
19
|
+
readonly channels: Readonly<Record<string, readonly number[]>>;
|
|
20
|
+
}
|
|
21
|
+
export interface WebAudioSourceOptions {
|
|
22
|
+
readonly audioContext?: AudioContext;
|
|
23
|
+
readonly fftSize?: number;
|
|
24
|
+
readonly smoothingTimeConstant?: number;
|
|
25
|
+
readonly bands?: Readonly<Record<string, readonly [number, number]>>;
|
|
26
|
+
readonly sampleRate?: number;
|
|
27
|
+
readonly onsetGain?: number;
|
|
28
|
+
readonly smoothing?: number;
|
|
29
|
+
readonly record?: boolean;
|
|
30
|
+
}
|
|
31
|
+
export interface WebAudioConnectOptions extends WebAudioSourceOptions {
|
|
32
|
+
readonly monitor?: boolean;
|
|
33
|
+
readonly loop?: boolean;
|
|
34
|
+
readonly autoplay?: boolean;
|
|
35
|
+
}
|
|
36
|
+
export interface WebAudioMicrophoneOptions extends WebAudioSourceOptions {
|
|
37
|
+
readonly constraints?: boolean | MediaTrackConstraints;
|
|
38
|
+
readonly monitor?: boolean;
|
|
39
|
+
}
|
|
40
|
+
interface InternalOptions extends WebAudioSourceOptions {
|
|
41
|
+
readonly ownedContext?: AudioContext;
|
|
42
|
+
readonly cleanup?: () => void;
|
|
43
|
+
readonly starter?: (when?: number, offset?: number) => void;
|
|
44
|
+
}
|
|
45
|
+
export declare class WebAudioChannelSource {
|
|
46
|
+
readonly ports: readonly string[];
|
|
47
|
+
readonly analyser: AnalyserLike;
|
|
48
|
+
readonly context?: AudioContext;
|
|
49
|
+
private readonly bands;
|
|
50
|
+
private readonly sampleRateOverride?;
|
|
51
|
+
private readonly onsetGain;
|
|
52
|
+
private readonly smoothing;
|
|
53
|
+
private readonly freqData;
|
|
54
|
+
private readonly prevSpectrum;
|
|
55
|
+
private readonly floatTimeData?;
|
|
56
|
+
private readonly byteTimeData?;
|
|
57
|
+
private readonly ownedContext?;
|
|
58
|
+
private readonly cleanup?;
|
|
59
|
+
private readonly starter?;
|
|
60
|
+
private hasPrevious;
|
|
61
|
+
private prevTimestamp?;
|
|
62
|
+
private prevValues?;
|
|
63
|
+
private travel;
|
|
64
|
+
private recording;
|
|
65
|
+
private recordedFrames;
|
|
66
|
+
private disposed;
|
|
67
|
+
constructor(analyser: AnalyserLike, options?: InternalOptions);
|
|
68
|
+
static fromMediaElement(element: HTMLMediaElement, options?: WebAudioConnectOptions): WebAudioChannelSource;
|
|
69
|
+
static fromAudioBuffer(buffer: AudioBuffer, options?: WebAudioConnectOptions): WebAudioChannelSource;
|
|
70
|
+
private static connectBuffer;
|
|
71
|
+
static fromFile(file: Blob | ArrayBuffer | string, options?: WebAudioConnectOptions): Promise<WebAudioChannelSource>;
|
|
72
|
+
static fromMediaStream(stream: MediaStream, options?: WebAudioConnectOptions): WebAudioChannelSource;
|
|
73
|
+
static fromMicrophone(options?: WebAudioMicrophoneOptions): Promise<WebAudioChannelSource>;
|
|
74
|
+
resume(): Promise<void>;
|
|
75
|
+
start(when?: number, offset?: number): void;
|
|
76
|
+
startRecording(): void;
|
|
77
|
+
stopRecording(): void;
|
|
78
|
+
reset(): void;
|
|
79
|
+
sample(frame?: number, time?: number): LiveChannelSample;
|
|
80
|
+
toChannelTable(sampleRate?: number): RecordedChannelTable;
|
|
81
|
+
dispose(): void;
|
|
82
|
+
private assertActive;
|
|
83
|
+
}
|
|
84
|
+
export {};
|
package/audio.js
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.WebAudioChannelSource = exports.DEFAULT_AUDIO_FEATURE_PORTS = exports.DEFAULT_AUDIO_BANDS = void 0;
|
|
4
|
+
exports.DEFAULT_AUDIO_BANDS = Object.freeze({
|
|
5
|
+
bass: Object.freeze([20, 250]),
|
|
6
|
+
mid: Object.freeze([250, 2000]),
|
|
7
|
+
treble: Object.freeze([2000, 16000]),
|
|
8
|
+
});
|
|
9
|
+
exports.DEFAULT_AUDIO_FEATURE_PORTS = Object.freeze([
|
|
10
|
+
'loudness', 'bass', 'mid', 'treble', 'onset', 'travel',
|
|
11
|
+
]);
|
|
12
|
+
function clampUnit(value) {
|
|
13
|
+
if (!Number.isFinite(value))
|
|
14
|
+
return 0;
|
|
15
|
+
return Math.max(0, Math.min(1, value));
|
|
16
|
+
}
|
|
17
|
+
function createAudioContext(provided) {
|
|
18
|
+
if (provided)
|
|
19
|
+
return { context: provided };
|
|
20
|
+
const AudioCtx = globalThis.AudioContext
|
|
21
|
+
?? globalThis.webkitAudioContext;
|
|
22
|
+
if (!AudioCtx)
|
|
23
|
+
throw new Error('Web Audio AudioContext is not available in this environment');
|
|
24
|
+
const context = new AudioCtx();
|
|
25
|
+
return { context, owned: context };
|
|
26
|
+
}
|
|
27
|
+
function configureAnalyser(context, options) {
|
|
28
|
+
const analyser = context.createAnalyser();
|
|
29
|
+
if (options.fftSize !== undefined)
|
|
30
|
+
analyser.fftSize = options.fftSize;
|
|
31
|
+
if (options.smoothingTimeConstant !== undefined) {
|
|
32
|
+
analyser.smoothingTimeConstant = options.smoothingTimeConstant;
|
|
33
|
+
}
|
|
34
|
+
return analyser;
|
|
35
|
+
}
|
|
36
|
+
function validateBands(bands) {
|
|
37
|
+
const entries = Object.entries(bands);
|
|
38
|
+
for (const [name, range] of entries) {
|
|
39
|
+
if (!name || name === 'loudness' || name === 'onset' || name === 'travel') {
|
|
40
|
+
throw new RangeError('Invalid audio band name: ' + name);
|
|
41
|
+
}
|
|
42
|
+
if (!Array.isArray(range) || range.length !== 2 || !Number.isFinite(range[0]) || !Number.isFinite(range[1]) || range[0] < 0 || range[0] >= range[1]) {
|
|
43
|
+
throw new RangeError('Invalid frequency band range for ' + name);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return entries;
|
|
47
|
+
}
|
|
48
|
+
class WebAudioChannelSource {
|
|
49
|
+
ports;
|
|
50
|
+
analyser;
|
|
51
|
+
context;
|
|
52
|
+
bands;
|
|
53
|
+
sampleRateOverride;
|
|
54
|
+
onsetGain;
|
|
55
|
+
smoothing;
|
|
56
|
+
freqData;
|
|
57
|
+
prevSpectrum;
|
|
58
|
+
floatTimeData;
|
|
59
|
+
byteTimeData;
|
|
60
|
+
ownedContext;
|
|
61
|
+
cleanup;
|
|
62
|
+
starter;
|
|
63
|
+
hasPrevious = false;
|
|
64
|
+
prevTimestamp;
|
|
65
|
+
prevValues;
|
|
66
|
+
travel = 0;
|
|
67
|
+
recording;
|
|
68
|
+
recordedFrames = new Map();
|
|
69
|
+
disposed = false;
|
|
70
|
+
constructor(analyser, options = {}) {
|
|
71
|
+
if (!analyser || typeof analyser.getByteFrequencyData !== 'function') {
|
|
72
|
+
throw new TypeError('An AnalyserNode-compatible analyser is required');
|
|
73
|
+
}
|
|
74
|
+
if (!Number.isInteger(analyser.frequencyBinCount) || analyser.frequencyBinCount <= 0) {
|
|
75
|
+
throw new RangeError('Analyser frequencyBinCount must be a positive integer');
|
|
76
|
+
}
|
|
77
|
+
const smoothing = options.smoothing ?? 0;
|
|
78
|
+
if (!Number.isFinite(smoothing) || smoothing < 0 || smoothing >= 1) {
|
|
79
|
+
throw new RangeError('Smoothing must be in [0, 1)');
|
|
80
|
+
}
|
|
81
|
+
const onsetGain = options.onsetGain ?? 4;
|
|
82
|
+
if (!Number.isFinite(onsetGain) || onsetGain <= 0) {
|
|
83
|
+
throw new RangeError('onsetGain must be finite and positive');
|
|
84
|
+
}
|
|
85
|
+
if (options.sampleRate !== undefined && (!Number.isFinite(options.sampleRate) || options.sampleRate <= 0)) {
|
|
86
|
+
throw new RangeError('sampleRate must be finite and positive');
|
|
87
|
+
}
|
|
88
|
+
this.analyser = analyser;
|
|
89
|
+
this.context = options.audioContext;
|
|
90
|
+
this.ownedContext = options.ownedContext;
|
|
91
|
+
this.cleanup = options.cleanup;
|
|
92
|
+
this.starter = options.starter;
|
|
93
|
+
this.sampleRateOverride = options.sampleRate;
|
|
94
|
+
this.onsetGain = onsetGain;
|
|
95
|
+
this.smoothing = smoothing;
|
|
96
|
+
this.recording = options.record ?? false;
|
|
97
|
+
const bandMap = options.bands ?? exports.DEFAULT_AUDIO_BANDS;
|
|
98
|
+
this.bands = validateBands(bandMap);
|
|
99
|
+
this.ports = Object.freeze(['loudness', ...this.bands.map(([name]) => name), 'onset', 'travel']);
|
|
100
|
+
this.freqData = new Uint8Array(analyser.frequencyBinCount);
|
|
101
|
+
this.prevSpectrum = new Float32Array(analyser.frequencyBinCount);
|
|
102
|
+
const timeSize = Math.max(1, analyser.fftSize || analyser.frequencyBinCount * 2);
|
|
103
|
+
if (typeof analyser.getFloatTimeDomainData === 'function') {
|
|
104
|
+
this.floatTimeData = new Float32Array(timeSize);
|
|
105
|
+
}
|
|
106
|
+
else if (typeof analyser.getByteTimeDomainData === 'function') {
|
|
107
|
+
this.byteTimeData = new Uint8Array(timeSize);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
static fromMediaElement(element, options = {}) {
|
|
111
|
+
const { context, owned } = createAudioContext(options.audioContext);
|
|
112
|
+
const monitor = options.monitor ?? true;
|
|
113
|
+
const analyser = configureAnalyser(context, options);
|
|
114
|
+
const node = context.createMediaElementSource(element);
|
|
115
|
+
node.connect(analyser);
|
|
116
|
+
if (monitor)
|
|
117
|
+
analyser.connect(context.destination);
|
|
118
|
+
const restoreOutput = () => {
|
|
119
|
+
try {
|
|
120
|
+
node.disconnect();
|
|
121
|
+
}
|
|
122
|
+
catch { /* ignore */ }
|
|
123
|
+
try {
|
|
124
|
+
analyser.disconnect();
|
|
125
|
+
}
|
|
126
|
+
catch { /* ignore */ }
|
|
127
|
+
if (!owned && monitor) {
|
|
128
|
+
try {
|
|
129
|
+
node.connect(context.destination);
|
|
130
|
+
}
|
|
131
|
+
catch { /* ignore */ }
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
try {
|
|
135
|
+
return new WebAudioChannelSource(analyser, {
|
|
136
|
+
...options,
|
|
137
|
+
audioContext: context,
|
|
138
|
+
ownedContext: owned,
|
|
139
|
+
starter: () => { void element.play(); },
|
|
140
|
+
cleanup: restoreOutput,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
restoreOutput();
|
|
145
|
+
if (owned)
|
|
146
|
+
void owned.close();
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
static fromAudioBuffer(buffer, options = {}) {
|
|
151
|
+
const { context, owned } = createAudioContext(options.audioContext);
|
|
152
|
+
return WebAudioChannelSource.connectBuffer(buffer, context, owned, options);
|
|
153
|
+
}
|
|
154
|
+
static connectBuffer(buffer, context, owned, options) {
|
|
155
|
+
const analyser = configureAnalyser(context, options);
|
|
156
|
+
const source = context.createBufferSource();
|
|
157
|
+
source.buffer = buffer;
|
|
158
|
+
source.loop = options.loop ?? false;
|
|
159
|
+
source.connect(analyser);
|
|
160
|
+
if (options.monitor ?? true)
|
|
161
|
+
analyser.connect(context.destination);
|
|
162
|
+
let started = false;
|
|
163
|
+
const startBuffer = (when, offset) => {
|
|
164
|
+
if (started)
|
|
165
|
+
return;
|
|
166
|
+
started = true;
|
|
167
|
+
source.start(when, offset);
|
|
168
|
+
};
|
|
169
|
+
const disconnect = () => {
|
|
170
|
+
if (started) {
|
|
171
|
+
try {
|
|
172
|
+
source.stop();
|
|
173
|
+
}
|
|
174
|
+
catch { /* ignore */ }
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
source.disconnect();
|
|
178
|
+
}
|
|
179
|
+
catch { /* ignore */ }
|
|
180
|
+
try {
|
|
181
|
+
analyser.disconnect();
|
|
182
|
+
}
|
|
183
|
+
catch { /* ignore */ }
|
|
184
|
+
};
|
|
185
|
+
try {
|
|
186
|
+
const channel = new WebAudioChannelSource(analyser, {
|
|
187
|
+
...options,
|
|
188
|
+
audioContext: context,
|
|
189
|
+
ownedContext: owned,
|
|
190
|
+
starter: startBuffer,
|
|
191
|
+
cleanup: disconnect,
|
|
192
|
+
});
|
|
193
|
+
if (options.autoplay)
|
|
194
|
+
channel.start();
|
|
195
|
+
return channel;
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
disconnect();
|
|
199
|
+
if (owned)
|
|
200
|
+
void owned.close();
|
|
201
|
+
throw error;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
static async fromFile(file, options = {}) {
|
|
205
|
+
const { context, owned } = createAudioContext(options.audioContext);
|
|
206
|
+
try {
|
|
207
|
+
let bytes;
|
|
208
|
+
if (typeof file === 'string') {
|
|
209
|
+
const response = await fetch(file);
|
|
210
|
+
if (!response.ok)
|
|
211
|
+
throw new Error(`Failed to fetch audio file (${response.status}): ${file}`);
|
|
212
|
+
bytes = await response.arrayBuffer();
|
|
213
|
+
}
|
|
214
|
+
else if (file instanceof ArrayBuffer) {
|
|
215
|
+
bytes = file.slice(0);
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
bytes = await file.arrayBuffer();
|
|
219
|
+
}
|
|
220
|
+
const buffer = await context.decodeAudioData(bytes);
|
|
221
|
+
return WebAudioChannelSource.connectBuffer(buffer, context, owned, options);
|
|
222
|
+
}
|
|
223
|
+
catch (error) {
|
|
224
|
+
if (owned)
|
|
225
|
+
void owned.close();
|
|
226
|
+
throw error;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
static fromMediaStream(stream, options = {}) {
|
|
230
|
+
const { context, owned } = createAudioContext(options.audioContext);
|
|
231
|
+
const analyser = configureAnalyser(context, options);
|
|
232
|
+
const node = context.createMediaStreamSource(stream);
|
|
233
|
+
node.connect(analyser);
|
|
234
|
+
if (options.monitor ?? false)
|
|
235
|
+
analyser.connect(context.destination);
|
|
236
|
+
return new WebAudioChannelSource(analyser, {
|
|
237
|
+
...options,
|
|
238
|
+
audioContext: context,
|
|
239
|
+
ownedContext: owned,
|
|
240
|
+
cleanup: () => {
|
|
241
|
+
try {
|
|
242
|
+
node.disconnect();
|
|
243
|
+
}
|
|
244
|
+
catch { /* ignore */ }
|
|
245
|
+
try {
|
|
246
|
+
analyser.disconnect();
|
|
247
|
+
}
|
|
248
|
+
catch { /* ignore */ }
|
|
249
|
+
},
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
static async fromMicrophone(options = {}) {
|
|
253
|
+
const mediaDevices = globalThis.navigator?.mediaDevices;
|
|
254
|
+
if (!mediaDevices || typeof mediaDevices.getUserMedia !== 'function') {
|
|
255
|
+
throw new Error('Microphone capture (navigator.mediaDevices.getUserMedia) is not available');
|
|
256
|
+
}
|
|
257
|
+
const stream = await mediaDevices.getUserMedia({ audio: options.constraints ?? true });
|
|
258
|
+
let owned;
|
|
259
|
+
let node;
|
|
260
|
+
let analyser;
|
|
261
|
+
try {
|
|
262
|
+
const ctx = createAudioContext(options.audioContext);
|
|
263
|
+
owned = ctx.owned;
|
|
264
|
+
analyser = configureAnalyser(ctx.context, options);
|
|
265
|
+
node = ctx.context.createMediaStreamSource(stream);
|
|
266
|
+
node.connect(analyser);
|
|
267
|
+
if (options.monitor ?? false)
|
|
268
|
+
analyser.connect(ctx.context.destination);
|
|
269
|
+
const connectedNode = node;
|
|
270
|
+
const connectedAnalyser = analyser;
|
|
271
|
+
return new WebAudioChannelSource(connectedAnalyser, {
|
|
272
|
+
...options,
|
|
273
|
+
audioContext: ctx.context,
|
|
274
|
+
ownedContext: owned,
|
|
275
|
+
cleanup: () => {
|
|
276
|
+
try {
|
|
277
|
+
connectedNode.disconnect();
|
|
278
|
+
}
|
|
279
|
+
catch { /* ignore */ }
|
|
280
|
+
try {
|
|
281
|
+
connectedAnalyser.disconnect();
|
|
282
|
+
}
|
|
283
|
+
catch { /* ignore */ }
|
|
284
|
+
for (const track of stream.getTracks())
|
|
285
|
+
track.stop();
|
|
286
|
+
},
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
try {
|
|
291
|
+
node?.disconnect();
|
|
292
|
+
}
|
|
293
|
+
catch { /* ignore */ }
|
|
294
|
+
try {
|
|
295
|
+
analyser?.disconnect();
|
|
296
|
+
}
|
|
297
|
+
catch { /* ignore */ }
|
|
298
|
+
for (const track of stream.getTracks())
|
|
299
|
+
track.stop();
|
|
300
|
+
if (owned)
|
|
301
|
+
void owned.close();
|
|
302
|
+
throw error;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
async resume() {
|
|
306
|
+
this.assertActive();
|
|
307
|
+
if (this.context && this.context.state === 'suspended') {
|
|
308
|
+
await this.context.resume();
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
start(when, offset) {
|
|
312
|
+
this.assertActive();
|
|
313
|
+
this.starter?.(when, offset);
|
|
314
|
+
}
|
|
315
|
+
startRecording() {
|
|
316
|
+
this.recording = true;
|
|
317
|
+
}
|
|
318
|
+
stopRecording() {
|
|
319
|
+
this.recording = false;
|
|
320
|
+
}
|
|
321
|
+
reset() {
|
|
322
|
+
this.hasPrevious = false;
|
|
323
|
+
this.prevTimestamp = undefined;
|
|
324
|
+
this.prevValues = undefined;
|
|
325
|
+
this.travel = 0;
|
|
326
|
+
this.prevSpectrum.fill(0);
|
|
327
|
+
this.recordedFrames.clear();
|
|
328
|
+
}
|
|
329
|
+
sample(frame = 0, time) {
|
|
330
|
+
this.assertActive();
|
|
331
|
+
this.analyser.getByteFrequencyData(this.freqData);
|
|
332
|
+
const binCount = this.freqData.length;
|
|
333
|
+
const sampleRate = this.sampleRateOverride ?? this.analyser.context?.sampleRate ?? 48000;
|
|
334
|
+
const nyquist = sampleRate / 2;
|
|
335
|
+
const hzPerBin = nyquist / binCount;
|
|
336
|
+
const rawValues = {};
|
|
337
|
+
for (const [name, [lowHz, highHz]] of this.bands) {
|
|
338
|
+
const startBin = Math.max(0, Math.min(binCount - 1, Math.ceil(lowHz / hzPerBin)));
|
|
339
|
+
const rawEnd = highHz / hzPerBin;
|
|
340
|
+
const endBin = Math.max(startBin, Math.min(binCount - 1, Number.isInteger(rawEnd) ? rawEnd - 1 : Math.floor(rawEnd)));
|
|
341
|
+
let sumSq = 0;
|
|
342
|
+
for (let i = startBin; i <= endBin; i++) {
|
|
343
|
+
const m = this.freqData[i] / 255;
|
|
344
|
+
sumSq += m * m;
|
|
345
|
+
}
|
|
346
|
+
rawValues[name] = clampUnit(Math.sqrt(sumSq / (endBin - startBin + 1)));
|
|
347
|
+
}
|
|
348
|
+
let loudness = 0;
|
|
349
|
+
if (this.floatTimeData && this.analyser.getFloatTimeDomainData) {
|
|
350
|
+
this.analyser.getFloatTimeDomainData(this.floatTimeData);
|
|
351
|
+
let sumSq = 0;
|
|
352
|
+
for (let i = 0; i < this.floatTimeData.length; i++) {
|
|
353
|
+
const v = this.floatTimeData[i];
|
|
354
|
+
sumSq += v * v;
|
|
355
|
+
}
|
|
356
|
+
loudness = clampUnit(Math.sqrt(sumSq / this.floatTimeData.length));
|
|
357
|
+
}
|
|
358
|
+
else if (this.byteTimeData && this.analyser.getByteTimeDomainData) {
|
|
359
|
+
this.analyser.getByteTimeDomainData(this.byteTimeData);
|
|
360
|
+
let sumSq = 0;
|
|
361
|
+
for (let i = 0; i < this.byteTimeData.length; i++) {
|
|
362
|
+
const v = (this.byteTimeData[i] - 128) / 128;
|
|
363
|
+
sumSq += v * v;
|
|
364
|
+
}
|
|
365
|
+
loudness = clampUnit(Math.sqrt(sumSq / this.byteTimeData.length));
|
|
366
|
+
}
|
|
367
|
+
else {
|
|
368
|
+
let sumSq = 0;
|
|
369
|
+
for (let i = 0; i < binCount; i++) {
|
|
370
|
+
const m = this.freqData[i] / 255;
|
|
371
|
+
sumSq += m * m;
|
|
372
|
+
}
|
|
373
|
+
loudness = clampUnit(Math.sqrt(sumSq / binCount));
|
|
374
|
+
}
|
|
375
|
+
rawValues.loudness = loudness;
|
|
376
|
+
let fluxSum = 0;
|
|
377
|
+
for (let i = 0; i < binCount; i++) {
|
|
378
|
+
const current = this.freqData[i] / 255;
|
|
379
|
+
if (this.hasPrevious) {
|
|
380
|
+
const diff = current - this.prevSpectrum[i];
|
|
381
|
+
if (diff > 0)
|
|
382
|
+
fluxSum += diff;
|
|
383
|
+
}
|
|
384
|
+
this.prevSpectrum[i] = current;
|
|
385
|
+
}
|
|
386
|
+
rawValues.onset = this.hasPrevious ? clampUnit((fluxSum / binCount) * this.onsetGain) : 0;
|
|
387
|
+
this.hasPrevious = true;
|
|
388
|
+
const timestamp = time !== undefined && Number.isFinite(time)
|
|
389
|
+
? time
|
|
390
|
+
: this.analyser.context?.currentTime ?? 0;
|
|
391
|
+
const dt = this.prevTimestamp !== undefined ? Math.max(0, timestamp - this.prevTimestamp) : 0;
|
|
392
|
+
this.prevTimestamp = timestamp;
|
|
393
|
+
this.travel += loudness * dt;
|
|
394
|
+
rawValues.travel = this.travel;
|
|
395
|
+
const values = {};
|
|
396
|
+
for (const port of this.ports) {
|
|
397
|
+
const raw = rawValues[port];
|
|
398
|
+
if (port === 'travel' || this.smoothing === 0 || !this.prevValues) {
|
|
399
|
+
values[port] = raw;
|
|
400
|
+
}
|
|
401
|
+
else {
|
|
402
|
+
values[port] = this.prevValues[port] * this.smoothing + raw * (1 - this.smoothing);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
this.prevValues = values;
|
|
406
|
+
if (this.recording && Number.isSafeInteger(frame) && frame >= 0 && !this.recordedFrames.has(frame)) {
|
|
407
|
+
this.recordedFrames.set(frame, { ...values });
|
|
408
|
+
}
|
|
409
|
+
return { timestamp, values };
|
|
410
|
+
}
|
|
411
|
+
toChannelTable(sampleRate = 30) {
|
|
412
|
+
if (!Number.isFinite(sampleRate) || sampleRate <= 0) {
|
|
413
|
+
throw new RangeError('Channel table sampleRate must be finite and positive');
|
|
414
|
+
}
|
|
415
|
+
if (!this.recordedFrames.size)
|
|
416
|
+
throw new Error('No recorded audio samples to export');
|
|
417
|
+
let maxFrame = 0;
|
|
418
|
+
for (const frame of this.recordedFrames.keys()) {
|
|
419
|
+
if (frame > maxFrame)
|
|
420
|
+
maxFrame = frame;
|
|
421
|
+
}
|
|
422
|
+
const channels = {};
|
|
423
|
+
for (const port of this.ports)
|
|
424
|
+
channels[port] = [];
|
|
425
|
+
let last;
|
|
426
|
+
for (let f = 0; f <= maxFrame; f++) {
|
|
427
|
+
const entry = this.recordedFrames.get(f) ?? last;
|
|
428
|
+
if (entry)
|
|
429
|
+
last = entry;
|
|
430
|
+
for (const port of this.ports)
|
|
431
|
+
channels[port].push(entry ? entry[port] : 0);
|
|
432
|
+
}
|
|
433
|
+
return {
|
|
434
|
+
sampleRate,
|
|
435
|
+
boundary: 'clamp',
|
|
436
|
+
interpolation: 'linear',
|
|
437
|
+
channels,
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
dispose() {
|
|
441
|
+
if (this.disposed)
|
|
442
|
+
return;
|
|
443
|
+
this.disposed = true;
|
|
444
|
+
this.cleanup?.();
|
|
445
|
+
if (this.ownedContext)
|
|
446
|
+
void this.ownedContext.close();
|
|
447
|
+
}
|
|
448
|
+
assertActive() {
|
|
449
|
+
if (this.disposed)
|
|
450
|
+
throw new Error('WebAudioChannelSource has been disposed');
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
exports.WebAudioChannelSource = WebAudioChannelSource;
|