-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathwebaudio-splice-test.html
More file actions
337 lines (289 loc) · 13.6 KB
/
webaudio-splice-test.html
File metadata and controls
337 lines (289 loc) · 13.6 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Audio Splice Test</title>
<style>
body { font-family: system-ui; background: #1a1a2e; color: #eee; padding: 40px; max-width: 800px; margin: 0 auto; }
.drop-zone { border: 2px dashed #555; border-radius: 12px; padding: 48px; text-align: center; cursor: pointer; transition: all 0.2s; }
.drop-zone.over { border-color: #4ade80; background: rgba(74, 222, 128, 0.1); }
button { background: #333; color: #eee; border: 1px solid #555; padding: 8px 16px; border-radius: 6px; cursor: pointer; margin: 4px; }
button:hover { background: #444; }
button:disabled { opacity: 0.4; cursor: default; }
canvas { width: 100%; height: 120px; background: #111; border-radius: 8px; cursor: crosshair; display: block; margin: 16px 0; }
.info { color: #888; font-size: 14px; margin: 8px 0; }
.controls { margin: 16px 0; }
h1 { color: #4ade80; }
#log { background: #111; padding: 12px; border-radius: 8px; font-family: monospace; font-size: 12px; max-height: 200px; overflow-y: auto; white-space: pre-wrap; }
</style>
</head>
<body>
<h1>Web Audio Splice Test</h1>
<p class="info">Debug tool: tests if splitting an audio buffer into two consecutive AudioBufferSourceNodes produces a click at the splice point. No SDK involved — pure Web Audio API.</p>
<div class="drop-zone" id="dropZone">
<p style="font-size: 20px">Drop an audio file here</p>
<p class="info">or click to browse</p>
<input type="file" accept="audio/*" id="fileInput" style="display:none">
</div>
<div id="ui" style="display:none">
<canvas id="waveform"></canvas>
<p class="info">Click = position playhead. Shift+Click = add split (red line). Play to hear across splice points.</p>
<div class="controls">
<label style="font-size: 14px; color: #aaa;">Fade samples: <input type="number" id="fadeSamples" value="128" min="0" max="8192" step="64" style="width:70px; background:#222; color:#eee; border:1px solid #555; padding:4px 8px; border-radius:4px;"></label>
<span class="info" id="fadeMs"></span>
<label style="font-size: 14px; color: #aaa; margin-left: 12px;"><input type="checkbox" id="overlapMode" checked> Overlap crossfade</label>
<button id="play">Play</button>
<button id="stop">Stop</button>
</div>
<p class="info" id="splitInfo">Split point: none</p>
<div id="log"></div>
</div>
<script>
let audioCtx = null;
let audioBuffer = null;
let splits = []; // array of sample indices where splits occur
let playheadSample = 0;
let currentSources = [];
let isPlaying = false;
let playStartTime = 0;
let playStartSample = 0;
let animFrameId = null;
const log = (msg) => {
const el = document.getElementById('log');
el.textContent += msg + '\n';
el.scrollTop = el.scrollHeight;
};
const dropZone = document.getElementById('dropZone');
const fileInput = document.getElementById('fileInput');
dropZone.addEventListener('click', () => fileInput.click());
dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('over'); });
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('over'));
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
dropZone.classList.remove('over');
const file = e.dataTransfer.files[0];
if (file) loadFile(file);
});
fileInput.addEventListener('change', (e) => {
if (e.target.files[0]) loadFile(e.target.files[0]);
});
async function loadFile(file) {
if (!audioCtx) audioCtx = new AudioContext();
log(`Decoding ${file.name} (${(file.size / 1024 / 1024).toFixed(1)} MB)...`);
try {
const arrayBuffer = await file.arrayBuffer();
audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);
} catch (e) {
log(`Error: Could not decode "${file.name}". ${e.message || e}`);
return;
}
log(`Decoded: ${audioBuffer.duration.toFixed(2)}s, ${audioBuffer.sampleRate}Hz, ${audioBuffer.numberOfChannels}ch, ${audioBuffer.length} samples`);
splits = [];
playheadSample = 0;
dropZone.style.display = 'none';
document.getElementById('ui').style.display = 'block';
updateSplitInfo();
updateFadeMs();
// Wait a frame for layout to resolve before drawing
requestAnimationFrame(() => drawWaveform());
}
window.addEventListener('resize', () => {
if (audioBuffer) drawWaveform();
});
function updateSplitInfo() {
const playSeconds = playheadSample / audioBuffer.sampleRate;
document.getElementById('splitInfo').textContent =
`Playhead: ${playSeconds.toFixed(3)}s | ${splits.length} split${splits.length !== 1 ? 's' : ''} → ${splits.length + 1} region${splits.length > 0 ? 's' : ''}`;
}
function drawWaveform() {
const canvas = document.getElementById('waveform');
const ctx = canvas.getContext('2d');
const dpr = window.devicePixelRatio || 1;
canvas.width = canvas.clientWidth * dpr;
canvas.height = canvas.clientHeight * dpr;
ctx.scale(dpr, dpr);
const w = canvas.clientWidth;
const h = canvas.clientHeight;
ctx.fillStyle = '#111';
ctx.fillRect(0, 0, w, h);
// Draw waveform (channel 0)
const data = audioBuffer.getChannelData(0);
const step = Math.ceil(data.length / w);
ctx.fillStyle = '#4ade80';
for (let x = 0; x < w; x++) {
const start = x * step;
let min = 0, max = 0;
for (let j = start; j < start + step && j < data.length; j++) {
if (data[j] < min) min = data[j];
if (data[j] > max) max = data[j];
}
const yMin = (1 + min) * h / 2;
const yMax = (1 + max) * h / 2;
ctx.fillRect(x, yMax, 1, yMin - yMax);
}
// Draw split lines (red dashed)
ctx.strokeStyle = 'rgba(255, 180, 80, 0.8)';
ctx.lineWidth = 1.5;
ctx.setLineDash([4, 4]);
for (const s of splits) {
const x = (s / audioBuffer.length) * w;
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, h);
ctx.stroke();
}
ctx.setLineDash([]);
// Draw playhead (white solid)
const phX = (playheadSample / audioBuffer.length) * w;
ctx.strokeStyle = '#fff';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(phX, 0);
ctx.lineTo(phX, h);
ctx.stroke();
}
document.getElementById('waveform').addEventListener('click', (e) => {
if (!audioBuffer || isPlaying) return;
const rect = e.target.getBoundingClientRect();
const fraction = (e.clientX - rect.left) / rect.width;
const sample = Math.round(fraction * audioBuffer.length);
if (e.shiftKey) {
// Shift+Click = add split
splits.push(sample);
splits.sort((a, b) => a - b);
log(`Split added at sample ${sample} (${(sample / audioBuffer.sampleRate).toFixed(4)}s) — ${splits.length + 1} regions`);
} else {
// Click = position playhead
playheadSample = sample;
}
updateSplitInfo();
drawWaveform();
});
function stopAll() {
currentSources.forEach(s => { try { s.stop(); } catch(e) { if (e.name !== 'InvalidStateError') console.warn('Error stopping source:', e); } });
currentSources = [];
isPlaying = false;
if (animFrameId) { cancelAnimationFrame(animFrameId); animFrameId = null; }
}
function updatePlayhead() {
if (!isPlaying) return;
const elapsed = audioCtx.currentTime - playStartTime;
playheadSample = Math.min(playStartSample + Math.round(elapsed * audioBuffer.sampleRate), audioBuffer.length);
drawWaveform();
updateSplitInfo();
if (playheadSample >= audioBuffer.length) { stopAll(); return; }
animFrameId = requestAnimationFrame(updatePlayhead);
}
document.getElementById('stop').addEventListener('click', () => {
stopAll();
drawWaveform();
});
// Update fade ms display
function updateFadeMs() {
const samples = parseInt(document.getElementById('fadeSamples').value) || 0;
const sr = audioBuffer ? audioBuffer.sampleRate : 48000;
document.getElementById('fadeMs').textContent = `(${(samples / sr * 1000).toFixed(1)}ms)`;
}
document.getElementById('fadeSamples').addEventListener('input', updateFadeMs);
// Play: schedule consecutive AudioBufferSourceNodes with optional crossfade
document.getElementById('play').addEventListener('click', async () => {
if (!audioBuffer) return;
stopAll();
if (audioCtx.state === 'suspended') await audioCtx.resume();
const fadeSamples = parseInt(document.getElementById('fadeSamples').value) || 0;
const overlap = document.getElementById('overlapMode').checked;
const sr = audioBuffer.sampleRate;
const fadeDur = fadeSamples / sr;
// Build region boundaries from splits
const boundaries = [0, ...splits, audioBuffer.length];
// Find which region the playhead is in
let startRegion = 0;
for (let i = 0; i < boundaries.length - 1; i++) {
if (playheadSample < boundaries[i + 1]) { startRegion = i; break; }
}
const now = audioCtx.currentTime + 0.05;
let scheduleTime = now;
const playheadOffset = playheadSample / sr;
const hasFade = fadeSamples > 0 && splits.length > 0;
const mode = hasFade ? (overlap ? 'overlap crossfade' : 'non-overlap fade') : 'no fade';
log(`Playing from ${playheadOffset.toFixed(4)}s across ${boundaries.length - 1 - startRegion} region(s) [${mode}${hasFade ? `, ${fadeSamples} samples / ${(fadeDur * 1000).toFixed(1)}ms` : ''}]`);
for (let i = startRegion; i < boundaries.length - 1; i++) {
const regionStartSample = boundaries[i];
const regionEndSample = boundaries[i + 1];
const regionStartSec = regionStartSample / sr;
const regionEndSec = regionEndSample / sr;
const isFirst = i === startRegion;
const isLast = i === boundaries.length - 2;
// For first region, start from playhead position
const offsetSec = isFirst ? playheadOffset : regionStartSec;
if (hasFade && overlap) {
// OVERLAP MODE: extend each region by fadeDur, crossfade during overlap
// Left region plays fadeDur longer, right region starts fadeDur earlier
const extendEnd = (!isLast) ? fadeDur : 0;
const earlyStart = (!isFirst) ? fadeDur : 0;
const srcOffset = offsetSec - earlyStart;
const srcDuration = (regionEndSec - offsetSec) + extendEnd + earlyStart;
if (srcDuration <= 0) continue;
const source = audioCtx.createBufferSource();
source.buffer = audioBuffer;
const gain = audioCtx.createGain();
source.connect(gain).connect(audioCtx.destination);
const regionScheduleTime = scheduleTime - earlyStart;
// Fade-in at the start (except first region)
if (!isFirst) {
gain.gain.setValueAtTime(0, regionScheduleTime);
gain.gain.linearRampToValueAtTime(1, regionScheduleTime + fadeDur);
}
// Fade-out at the end (except last region)
if (!isLast) {
const fadeOutStart = scheduleTime + (regionEndSec - offsetSec);
gain.gain.setValueAtTime(1, fadeOutStart);
gain.gain.linearRampToValueAtTime(0, fadeOutStart + fadeDur);
}
source.start(regionScheduleTime, srcOffset, srcDuration);
currentSources.push(source);
log(` region ${i}: offset=${srcOffset.toFixed(4)}s dur=${srcDuration.toFixed(4)}s @ t+${(regionScheduleTime - now).toFixed(4)}s${!isFirst ? ' (early start)' : ''}${!isLast ? ' (extended end)' : ''}`);
scheduleTime += (regionEndSec - offsetSec);
} else if (hasFade && !overlap) {
// NON-OVERLAP MODE: fade-out/fade-in at boundaries, no overlap
const durationSec = regionEndSec - offsetSec;
if (durationSec <= 0) continue;
const source = audioCtx.createBufferSource();
source.buffer = audioBuffer;
const gain = audioCtx.createGain();
source.connect(gain).connect(audioCtx.destination);
if (!isLast) {
const fadeOutStart = scheduleTime + durationSec - fadeDur;
gain.gain.setValueAtTime(1, fadeOutStart);
gain.gain.linearRampToValueAtTime(0, fadeOutStart + fadeDur);
}
if (!isFirst) {
gain.gain.setValueAtTime(0, scheduleTime);
gain.gain.linearRampToValueAtTime(1, scheduleTime + fadeDur);
}
source.start(scheduleTime, offsetSec, durationSec);
currentSources.push(source);
log(` region ${i}: ${offsetSec.toFixed(4)}s — ${regionEndSec.toFixed(4)}s @ t+${(scheduleTime - now).toFixed(4)}s`);
scheduleTime += durationSec;
} else {
// NO FADE: simple consecutive scheduling
const durationSec = regionEndSec - offsetSec;
if (durationSec <= 0) continue;
const source = audioCtx.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioCtx.destination);
source.start(scheduleTime, offsetSec, durationSec);
currentSources.push(source);
log(` region ${i}: ${offsetSec.toFixed(4)}s — ${regionEndSec.toFixed(4)}s @ t+${(scheduleTime - now).toFixed(4)}s`);
scheduleTime += durationSec;
}
}
isPlaying = true;
playStartTime = now;
playStartSample = playheadSample;
animFrameId = requestAnimationFrame(updatePlayhead);
});
</script>
</body>
</html>