/**
* Page-turn sound and background audio (Pro).
*
* The page-turn sound is synthesised (filtered noise with a short envelope),
* so there is no audio file to download or license.
*/
export interface AudioTrack {
url: string;
title?: string;
/** Start on the reader's first click or key press in the viewer */
autoplay?: boolean;
}
let context: AudioContext | null = null;
let noise: AudioBuffer | null = null;
let lastFlip = 0;
function audioContext(): AudioContext | null {
if (context) return context;
const Ctor = window.AudioContext || (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
if (!Ctor) return null;
context = new Ctor();
return context;
}
/** A soft paper "swish". Safe to call often: rapid calls are thinned out. */
export function playPageTurn(volume = 0.6): void {
const now = performance.now();
if (now - lastFlip < 90) return; // fast multi-page jumps
lastFlip = now;
const ctx = audioContext();
if (!ctx) return;
if (ctx.state === 'suspended') void ctx.resume();
if (!noise) {
const length = Math.floor(ctx.sampleRate * 0.5);
noise = ctx.createBuffer(1, length, ctx.sampleRate);
const data = noise.getChannelData(0);
let last = 0;
for (let i = 0; i < length; i++) {
// Slightly "pink" noise sounds more like paper than white noise.
last = 0.82 * last + 0.18 * (Math.random() * 2 - 1);
data[i] = last * 3;
}
}
const t = ctx.currentTime;
const duration = 0.32 + Math.random() * 0.08;
const source = ctx.createBufferSource();
source.buffer = noise;
source.playbackRate.value = 0.9 + Math.random() * 0.25;
const band = ctx.createBiquadFilter();
band.type = 'bandpass';
band.Q.value = 0.7;
band.frequency.setValueAtTime(1800, t);
band.frequency.exponentialRampToValueAtTime(4200, t + duration * 0.45);
band.frequency.exponentialRampToValueAtTime(1400, t + duration);
const gain = ctx.createGain();
const peak = Math.max(0, Math.min(1, volume)) * 0.5;
gain.gain.setValueAtTime(0.0001, t);
gain.gain.exponentialRampToValueAtTime(peak, t + duration * 0.35);
gain.gain.exponentialRampToValueAtTime(0.0001, t + duration);
source.connect(band).connect(gain).connect(ctx.destination);
source.start(t, Math.random() * 0.1, duration);
}
const MUSIC_ICON = '';
const PAUSE_ICON = '';
/**
* Background track with a play/pause button in the viewer's corner.
* Returns a cleanup function.
*/
export function mountBackgroundAudio(container: HTMLElement, track: AudioTrack): () => void {
const audio = new Audio();
audio.src = track.url;
audio.loop = true;
audio.preload = 'none';
audio.volume = 0.7;
const button = document.createElement('button');
button.type = 'button';
button.className = 'pdfrack-audio-toggle';
container.appendChild(button);
const label = track.title ? `background audio: ${track.title}` : 'background audio';
const render = () => {
const playing = !audio.paused;
button.innerHTML = playing
? `${PAUSE_ICON}`
: MUSIC_ICON;
button.classList.toggle('is-playing', playing);
button.setAttribute('aria-pressed', String(playing));
button.setAttribute('aria-label', `${playing ? 'Pause' : 'Play'} ${label}`);
button.title = `${playing ? 'Pause' : 'Play'} ${label}`;
};
const play = () => audio.play().catch(() => { /* blocked until a gesture */ });
button.addEventListener('click', (e) => {
e.stopPropagation();
disarm();
if (audio.paused) void play();
else audio.pause();
});
audio.addEventListener('play', render);
audio.addEventListener('pause', render);
render();
// "Autoplay": start on the first interaction inside the viewer.
const kick = (e: Event) => {
if (button.contains(e.target as Node)) return;
disarm();
if (audio.paused) void play();
};
const disarm = () => {
container.removeEventListener('pointerdown', kick, true);
container.removeEventListener('keydown', kick, true);
};
if (track.autoplay) {
container.addEventListener('pointerdown', kick, true);
container.addEventListener('keydown', kick, true);
}
// Don't keep playing in a background tab.
const onHidden = () => {
if (document.hidden && !audio.paused) audio.pause();
};
document.addEventListener('visibilitychange', onHidden);
return () => {
disarm();
document.removeEventListener('visibilitychange', onHidden);
audio.pause();
audio.removeAttribute('src');
audio.load();
button.remove();
};
}