main.js (18.3 KB)
1 // The head is the middle slot, above the record button. 2 const SLOTS = 51; 3 const HEAD = (SLOTS - 1) / 2; 4 const SPIN_UP_SECONDS = 0.4; 5 // Independent of the starting speed. 6 const SPIN_DOWN_SECONDS = 0.7; 7 // A finger resting on a playing tape brakes it after this. A volume drag that 8 // begins sooner leaves the tape alone. 9 const PRESS_DELAY_MILLISECONDS = 150; 10 // In CSS px. 11 const DRAG_THRESHOLD = 5; 12 const APPEAR_MILLISECONDS = 300; 13 // A deleted row fades out faster than it shrinks. 14 const DELETE_FADE_MILLISECONDS = 200; 15 const HOLD_TO_DELETE_MILLISECONDS = 2000; 16 const UPCOMING_OPACITY = 0.35; 17 const MAX_VOLUME = 2; 18 // Time constant of bar height changes. 19 const BAR_EASE_SECONDS = 0.035; 20 // Throttle scroll speed grows with drag distance up to SCROLL_FULL_DRAG px, where it 21 // reaches SCROLL_TOP_SPEED px/s. 22 const SCROLL_FULL_DRAG = 100; 23 const SCROLL_TOP_SPEED = 1000; 24 // Sideways drag distance, in CSS px, that changes a tape's speed by 1. 25 const THROTTLE_DRAG = 100; 26 // The iOS built-in microphone is super quiet with processing off, and while it is 27 // open the speaker plays quieter. These gains compensate. 28 const BUILT_IN_MICROPHONE_GAIN = 20; 29 const BUILT_IN_PLAYBACK_GAIN = 2; 30 31 const tapesElement = document.querySelector('#tapes'); 32 const recordButton = document.querySelector('#record'); 33 34 // A tape's index is its id on the audio thread. A deleted tape leaves a null behind. 35 const tapes = []; 36 let recording = null; 37 // A promise of the screen wake lock held during a take. 38 let wakeLock = null; 39 let audio = null; 40 let deck = null; 41 let setup = null; 42 let microphone = null; 43 let microphoneOpening = null; 44 // Decides whether the microphone is reopened when the page returns. 45 let microphoneUsed = false; 46 let microphoneRepaired = false; 47 48 const database = new Promise((resolve, reject) => { 49 const request = indexedDB.open('soundstone', 1); 50 request.onupgradeneeded = () => { 51 request.result.createObjectStore('tapes', {autoIncrement: true}); 52 request.result.createObjectStore('samples'); 53 }; 54 request.onsuccess = () => resolve(request.result); 55 request.onerror = () => reject(request.error); 56 }); 57 58 const settled = request => new Promise((resolve, reject) => { 59 request.onsuccess = () => resolve(request.result); 60 request.onerror = () => reject(request.error); 61 }); 62 63 // Resolves to the storage key. 64 async function saveTape(tape, samples) { 65 const transaction = (await database).transaction(['tapes', 'samples'], 'readwrite'); 66 const key = await settled(transaction.objectStore('tapes').add({ 67 peaks: tape.peaks, 68 length: tape.length, 69 volume: tape.volume, 70 sampleRate: audio.sampleRate, 71 })); 72 transaction.objectStore('samples').put(samples, key); 73 return key; 74 } 75 76 async function saveVolume(tape) { 77 const key = await tape.saved; 78 const store = (await database).transaction('tapes', 'readwrite').objectStore('tapes'); 79 const record = await settled(store.get(key)); 80 record.volume = tape.volume; 81 store.put(record, key); 82 } 83 84 async function forgetTape(tape) { 85 const key = await tape.saved; 86 const transaction = (await database).transaction(['tapes', 'samples'], 'readwrite'); 87 transaction.objectStore('tapes').delete(key); 88 transaction.objectStore('samples').delete(key); 89 } 90 91 // The device rate can change between visits, eg with headphones. Converting keeps the pitch. 92 async function resample(samples, rate) { 93 if (rate === audio.sampleRate) return samples; 94 const length = Math.round(samples.length * audio.sampleRate / rate); 95 const offline = new OfflineAudioContext(1, length, audio.sampleRate); 96 const source = offline.createBufferSource(); 97 source.buffer = new AudioBuffer({length: samples.length, sampleRate: rate}); 98 source.buffer.copyToChannel(samples, 0); 99 source.connect(offline.destination); 100 source.start(); 101 return (await offline.startRendering()).getChannelData(0); 102 } 103 104 async function loadTapes() { 105 const transaction = (await database).transaction(['tapes', 'samples']); 106 const [keys, records, takes] = await Promise.all([ 107 settled(transaction.objectStore('tapes').getAllKeys()), 108 settled(transaction.objectStore('tapes').getAll()), 109 settled(transaction.objectStore('samples').getAll()), 110 ]); 111 for (const [i, {peaks, length, volume, sampleRate}] of records.entries()) { 112 const samples = await resample(takes[i], sampleRate); 113 deck.port.postMessage({type: 'load', samples, volume}); 114 const tape = addTape({peaks, length, volume, saved: keys[i]}); 115 makeGrabbable(tape, tapes.length); 116 tapes.push(tape); 117 } 118 tapesElement.scrollTop = tapesElement.scrollHeight; 119 } 120 121 // Runs on load. Audio stays suspended until the first touch, but saved tapes load meanwhile. 122 async function setUpAudio() { 123 audio = new AudioContext(); 124 await audio.audioWorklet.addModule('resources/deck.js'); 125 deck = new AudioWorkletNode(audio, 'deck', { 126 outputChannelCount: [1], 127 processorOptions: { 128 spinUpSeconds: SPIN_UP_SECONDS, 129 spinDownSeconds: SPIN_DOWN_SECONDS, 130 deleteSeconds: APPEAR_MILLISECONDS / 1000, 131 }, 132 }); 133 deck.connect(audio.destination); 134 deck.port.onmessage = ({data}) => handlers[data.type](data); 135 // The system can interrupt the audio, as it does at lock in Safari. 136 audio.onstatechange = () => { 137 if (audio.state !== 'running') endTake(); 138 }; 139 setAudioSessionType('playback'); 140 await loadTapes(); 141 } 142 143 // Safari only. The type decides whether sound continues while the device is locked. 144 function setAudioSessionType(type) { 145 if (navigator.audioSession) navigator.audioSession.type = type; 146 } 147 148 function openMicrophone() { 149 microphoneOpening ??= (async () => { 150 setAudioSessionType('play-and-record'); 151 const stream = await navigator.mediaDevices.getUserMedia({ 152 audio: {echoCancellation: false, noiseSuppression: false, autoGainControl: false}, 153 }); 154 const source = audio.createMediaStreamSource(stream); 155 source.connect(deck); 156 const [track] = stream.getAudioTracks(); 157 // The system mutes or ends the track when it cuts the microphone. 158 track.onmute = track.onended = endTake; 159 // iOS names the built-in microphone after the device, as in "iPhone Microphone". 160 const builtIn = /iPhone|iPad/.test(track.label); 161 deck.port.postMessage({ 162 type: 'microphone', 163 gain: builtIn ? BUILT_IN_MICROPHONE_GAIN : 1, 164 playbackGain: builtIn ? BUILT_IN_PLAYBACK_GAIN : 1, 165 }); 166 microphone = {stream, source}; 167 microphoneUsed = true; 168 })().finally(() => microphoneOpening = null); 169 return microphoneOpening; 170 } 171 172 function closeMicrophone() { 173 microphone.source.disconnect(); 174 for (const track of microphone.stream.getTracks()) track.stop(); 175 microphone = null; 176 deck.port.postMessage({type: 'playbackGain', value: 1}); 177 } 178 179 // iOS can get stuck delivering silence to an unprocessed microphone, across 180 // launches. A hacky attempt at fixing this. 181 async function repairMicrophone() { 182 if (!microphone || microphoneRepaired) return; 183 microphoneRepaired = true; 184 const stream = await navigator.mediaDevices.getUserMedia({audio: true}); 185 for (const track of stream.getTracks()) track.stop(); 186 if (!microphone) return; 187 closeMicrophone(); 188 await openMicrophone(); 189 } 190 191 // In Safari an open microphone stops audio at lock, so it is released while 192 // hidden once no take is in progress. 193 function releaseHiddenMicrophone() { 194 if (!navigator.audioSession || !document.hidden || !microphone || recording) return; 195 closeMicrophone(); 196 setAudioSessionType('playback'); 197 } 198 199 document.addEventListener('visibilitychange', async () => { 200 if (!navigator.audioSession || !deck) return; 201 if (!document.hidden) { 202 audio.resume(); 203 if (microphoneUsed && !microphone) await openMicrophone(); 204 } 205 releaseHiddenMicrophone(); 206 }); 207 208 const handlers = { 209 peak({value}) { 210 recording.peaks.push(value); 211 }, 212 213 tape({peaks, length, samples}) { 214 const tape = recording; 215 recording = null; 216 tape.peaks = peaks; 217 tape.length = length; 218 tape.saved = saveTape(tape, samples); 219 tape.recording = false; 220 tape.redraw = true; 221 makeGrabbable(tape, tapes.length); 222 tapes.push(tape); 223 releaseHiddenMicrophone(); 224 }, 225 226 silent() { 227 repairMicrophone(); 228 }, 229 230 discard() { 231 recording.row.remove(); 232 recording = null; 233 releaseHiddenMicrophone(); 234 }, 235 236 direction({id, direction}) { 237 if (tapes[id]) tapes[id].direction = direction; 238 }, 239 240 positions({positions}) { 241 positions.forEach((position, id) => { 242 if (tapes[id]) tapes[id].position = position; 243 }); 244 }, 245 }; 246 247 function addTape(fields) { 248 const row = document.createElement('div'); 249 row.className = 'tape'; 250 const canvas = row.appendChild(document.createElement('canvas')); 251 tapesElement.append(row); 252 const tape = { 253 row, 254 canvas, 255 peaks: [], 256 // In bars; not always whole. 257 length: 0, 258 // Head position, in bars. 259 position: 0, 260 recording: false, 261 // 1, -1, or 0 when stopped. 262 direction: 0, 263 volume: 1, 264 // Drawn bar lengths in canvas px, trailing their targets. 265 lengths: null, 266 // Dimming left and right of the head, 0 to 1. 267 dim: [0, 0], 268 redraw: true, 269 // Storage key, or a promise of it while saving. 270 saved: null, 271 ...fields, 272 }; 273 fit(tape); 274 return tape; 275 } 276 277 function endTake() { 278 if (!recording) return; 279 deck.port.postMessage({type: 'stop'}); 280 recordButton.classList.remove('recording'); 281 wakeLock?.then(lock => lock.release()); 282 wakeLock = null; 283 } 284 285 async function toggleRecording() { 286 if (recording) return endTake(); 287 // Only a press may start audio, and it stops counting once the microphone 288 // prompt is answered, so resume before awaiting. 289 audio.resume(); 290 await setup; 291 if (!microphone) await openMicrophone(); 292 if (recording) return; 293 audio.resume(); 294 295 recording = addTape({recording: true}); 296 const {row} = recording; 297 deck.port.postMessage({type: 'record'}); 298 recordButton.classList.add('recording'); 299 // Keeps the screen from locking by itself, which would cut the microphone. 300 wakeLock = navigator.wakeLock?.request('screen'); 301 302 row.animate( 303 [{height: 0, opacity: 0}, {}], 304 {duration: APPEAR_MILLISECONDS, easing: 'ease-out'}, 305 ); 306 const scrollStart = tapesElement.scrollTop; 307 const began = performance.now(); 308 const follow = now => { 309 const progress = Math.min(1, Math.max(0, (now - began) / APPEAR_MILLISECONDS)); 310 const bottom = tapesElement.scrollHeight - tapesElement.clientHeight; 311 tapesElement.scrollTop = scrollStart + (bottom - scrollStart) * (1 - (1 - progress) ** 3); 312 if (progress < 1) requestAnimationFrame(follow); 313 }; 314 requestAnimationFrame(follow); 315 } 316 317 // pointerdown, because a second finger on the screen produces no click. 318 // The click listener serves the keyboard (detail 0). 319 recordButton.addEventListener('pointerdown', toggleRecording); 320 recordButton.addEventListener('click', event => { 321 if (event.detail === 0) toggleRecording(); 322 }); 323 324 function makeGrabbable(tape, id) { 325 const {row} = tape; 326 const send = (type, fields) => deck.port.postMessage({type, id, ...fields}); 327 let start = null; 328 let mode = null; 329 let wasPlaying = false; 330 // This pointer has started braking the tape. 331 let pressed = false; 332 let pressTimer = null; 333 let holdTimer = null; 334 // One pointer per tape, so several tapes can be touched at once. 335 let pointerId = null; 336 row.classList.add('finished'); 337 338 const remove = () => { 339 start = null; 340 send('delete'); 341 forgetTape(tape); 342 tapes[id] = null; 343 row.classList.remove('finished'); 344 row.animate([{}, {opacity: 0}], {duration: DELETE_FADE_MILLISECONDS, easing: 'ease-out', fill: 'forwards'}); 345 row.animate( 346 [{}, {height: 0}], 347 {duration: APPEAR_MILLISECONDS, easing: 'ease-out'}, 348 ).finished.then(() => row.remove()); 349 }; 350 351 row.addEventListener('pointerdown', event => { 352 if (pointerId !== null) return; 353 if (event.shiftKey) { 354 remove(); 355 return; 356 } 357 audio.resume(); 358 pointerId = event.pointerId; 359 row.setPointerCapture(pointerId); 360 row.classList.add('grabbed'); 361 start = {x: event.clientX, y: event.clientY, volume: tape.volume}; 362 mode = null; 363 wasPlaying = tape.direction !== 0; 364 pressed = false; 365 if (wasPlaying) { 366 pressTimer = setTimeout(() => { 367 pressed = true; 368 send('press'); 369 }, PRESS_DELAY_MILLISECONDS); 370 } 371 holdTimer = setTimeout(remove, HOLD_TO_DELETE_MILLISECONDS); 372 }); 373 374 row.addEventListener('pointermove', event => { 375 if (event.pointerId !== pointerId || !start) return; 376 if (!mode) { 377 const acrossTravel = Math.abs(event.clientX - start.x); 378 const upTravel = Math.abs(event.clientY - start.y); 379 if (Math.max(acrossTravel, upTravel) < DRAG_THRESHOLD) return; 380 if (acrossTravel < upTravel && pressed) return; 381 mode = acrossTravel >= upTravel ? 'throttle' : 'volume'; 382 clearTimeout(pressTimer); 383 clearTimeout(holdTimer); 384 // Browsers suspend audio until the first tap or click; a dragged touch 385 // doesn't count. Ignore a throttle drag before then, as the tape can't play. 386 if (mode === 'throttle' && audio.state !== 'running') mode = 'ignored'; 387 if (mode !== 'ignored') row.classList.add(mode); 388 if (mode === 'throttle') send('grab'); 389 pressed = false; 390 } 391 if (mode === 'throttle') { 392 send('throttle', {change: (event.clientX - start.x) / THROTTLE_DRAG}); 393 } else if (mode === 'volume') { 394 const change = (start.y - event.clientY) / row.clientHeight; 395 tape.volume = Math.min(MAX_VOLUME, Math.max(0, start.volume + change)); 396 send('volume', {value: tape.volume}); 397 } 398 }); 399 400 const end = event => { 401 if (event.pointerId !== pointerId) return; 402 pointerId = null; 403 // A touch only counts as a user gesture when it lifts without having moved, 404 // so the resume on pointerdown fails if this touch is the first one. 405 audio.resume(); 406 clearTimeout(pressTimer); 407 clearTimeout(holdTimer); 408 row.classList.remove('grabbed', 'throttle', 'volume'); 409 if (!start) return; 410 start = null; 411 if (mode === 'volume') saveVolume(tape); 412 if (mode === 'throttle') { 413 send('release'); 414 } else if (!mode && event.type === 'pointerup') { 415 if (wasPlaying) { 416 send('brake'); 417 tape.direction = 0; 418 } else { 419 const box = row.getBoundingClientRect(); 420 tape.direction = event.clientX < (box.left + box.right) / 2 ? -1 : 1; 421 send('play', {speed: tape.direction}); 422 } 423 } else if (pressed) { 424 send('drop'); 425 } 426 pressed = false; 427 }; 428 row.addEventListener('pointerup', end); 429 row.addEventListener('pointercancel', end); 430 } 431 432 // Throttle control: while held, scroll speed follows the offset from the press point. 433 const footer = document.querySelector('footer'); 434 let scrollDrag = null; 435 436 footer.addEventListener('pointerdown', event => { 437 if (scrollDrag || event.target === recordButton) return; 438 footer.setPointerCapture(event.pointerId); 439 scrollDrag = {pointerId: event.pointerId, startY: event.clientY, y: event.clientY}; 440 let last = performance.now(); 441 const step = now => { 442 if (!scrollDrag) return; 443 const pull = Math.min(1, Math.max(-1, (scrollDrag.y - scrollDrag.startY) / SCROLL_FULL_DRAG)); 444 tapesElement.scrollTop += pull * SCROLL_TOP_SPEED * Math.max(0, now - last) / 1000; 445 last = now; 446 requestAnimationFrame(step); 447 }; 448 requestAnimationFrame(step); 449 }); 450 451 footer.addEventListener('pointermove', event => { 452 if (scrollDrag?.pointerId === event.pointerId) scrollDrag.y = event.clientY; 453 }); 454 455 const endScrollDrag = event => { 456 if (scrollDrag?.pointerId === event.pointerId) scrollDrag = null; 457 }; 458 footer.addEventListener('pointerup', endScrollDrag); 459 footer.addEventListener('pointercancel', endScrollDrag); 460 461 function fit(tape) { 462 const {width, height} = tape.canvas.getBoundingClientRect(); 463 tape.canvas.width = Math.round(width * devicePixelRatio); 464 tape.canvas.height = Math.round(height * devicePixelRatio); 465 tape.lengths = null; 466 } 467 468 addEventListener('resize', () => { 469 tapes.filter(Boolean).forEach(fit); 470 if (recording) fit(recording); 471 }); 472 473 // Null where there is no tape. 474 function peakAt(tape, slot) { 475 const offset = slot - HEAD; 476 const {peaks, length} = tape; 477 if (tape.recording) { 478 const index = peaks.length + offset; 479 return offset < 0 && index >= 0 ? peaks[index] : null; 480 } 481 // Blend the two bars a slot lies between, so motion is smooth across the loop point. 482 const bar = ((tape.position + offset) % length + length) % length; 483 const index = Math.min(Math.floor(bar), peaks.length - 1); 484 const next = (index + 1) % peaks.length; 485 // The last bar of a tape can be shorter than the others. 486 const span = Math.min(1, length - index); 487 return peaks[index] + (peaks[next] - peaks[index]) * (bar - index) / span; 488 } 489 490 // Eases bars and dimming towards their targets; redraws only on change. 491 function animate(tape, seconds) { 492 const {canvas} = tape; 493 const {width, height} = canvas; 494 const pitch = width / SLOTS; 495 const thickness = pitch * 0.42; 496 const shortest = thickness * 2.5; 497 let changed = tape.redraw; 498 tape.redraw = false; 499 500 const snap = !tape.lengths; 501 tape.lengths ??= new Float32Array(SLOTS); 502 const ease = snap ? 1 : 1 - Math.exp(-seconds / BAR_EASE_SECONDS); 503 const recorded = []; 504 for (let slot = 0; slot < SLOTS; slot++) { 505 const peak = peakAt(tape, slot); 506 recorded[slot] = peak !== null; 507 const wanted = peak === null 508 ? thickness 509 : shortest + (height * 0.85 - shortest) * Math.min(1, peak * tape.volume) ** 0.6; 510 const gap = wanted - tape.lengths[slot]; 511 if (Math.abs(gap) < 0.1) continue; 512 tape.lengths[slot] += gap * ease; 513 changed = true; 514 } 515 516 // Dim the side about to play, over the spin-down time. 517 const wantedDim = [tape.direction < 0 ? 1 : 0, tape.direction > 0 ? 1 : 0]; 518 for (const side of [0, 1]) { 519 const gap = wantedDim[side] - tape.dim[side]; 520 if (gap === 0) continue; 521 tape.dim[side] += Math.sign(gap) * Math.min(Math.abs(gap), seconds / SPIN_DOWN_SECONDS); 522 changed = true; 523 } 524 525 if (!changed) return; 526 const context = canvas.getContext('2d'); 527 context.clearRect(0, 0, width, height); 528 context.lineCap = 'round'; 529 context.lineWidth = thickness; 530 for (let slot = 0; slot < SLOTS; slot++) { 531 const reach = Math.max(tape.lengths[slot] - thickness, 0.01) / 2; 532 const x = (slot + 0.5) * pitch; 533 const dim = slot === HEAD ? 0 : tape.dim[slot < HEAD ? 0 : 1]; 534 context.globalAlpha = 1 - dim * (1 - UPCOMING_OPACITY); 535 context.strokeStyle = tape.recording && recorded[slot] ? '#f00' : '#fff'; 536 context.beginPath(); 537 context.moveTo(x, height / 2 - reach); 538 context.lineTo(x, height / 2 + reach); 539 context.stroke(); 540 } 541 } 542 543 let lastFrame = performance.now(); 544 function frame(now) { 545 const seconds = (now - lastFrame) / 1000; 546 lastFrame = now; 547 for (const tape of tapes) { 548 if (tape) animate(tape, seconds); 549 } 550 if (recording) animate(recording, seconds); 551 requestAnimationFrame(frame); 552 } 553 requestAnimationFrame(frame); 554 555 if (navigator.mediaSession) { 556 navigator.mediaSession.metadata = new MediaMetadata({ 557 title: 'new soundscape', 558 artist: 'soundstone', 559 artwork: [{src: 'resources/icon.png', sizes: '1024x1024', type: 'image/png'}], 560 }); 561 } 562 563 setup = setUpAudio(); 564 565 // Skipped on localhost so edits show on the first reload. 566 if ('serviceWorker' in navigator && !['localhost', '127.0.0.1'].includes(location.hostname)) { 567 navigator.serviceWorker.register('service-worker.js'); 568 }