music.ts

examples/fractals/demo/music.ts · raw · open the example · all examples · site home

Exports: AUDIO_ROOTClockMusicWallClockFileMusicGpuMusic

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
// A demo's music and the clock the picture follows. Two sources, the same
// mix: the tune rendered ahead of time to an AAC file (by default: a small
// download, decoded whole into Web Audio, so
// it never starves and the clock stays sample-accurate) or synthesized live
// on the GPU (film/gpuAudio.ts, streamed to an AudioWorklet; WebGPU only).
// The file is looked for at ?audio= (a folder), else the hosted folder,
// else build/data/fractals/ from the server's root (npm run serve);
// `failed` once none has it (the demo then synthesizes or plays silent).
// Both pause by suspending their audio context, which stops the clock.
import type { WebGPURenderer } from "three/webgpu";
import { ScoreStream, heardTime } from "../../film/audioStream.js";
import { GpuScore } from "../../film/gpuAudio.js";
import type { ScoreData } from "../../film/score.js";

// The hosted files: the dated GCS folder of scripts/data.mjs
export const AUDIO_ROOT = "https://storage.googleapis.com/forge-dev-public/asundqui/radix/261011/fractals/";

export interface Clock {
  time(): number;
  play(): void;
  pause(): void;
  resume(): void;
  restart(): void;
}

export interface Music extends Clock {
  kind: "file" | "gpu";
  failed: boolean;
  // Rendered (or loaded) far enough ahead of the playhead, and how far
  ready(seconds: number): boolean;
  ahead(): number;
  // From a user gesture: lets the audio context start
  unlock(): void;
  // 0..1 (heard as its square, closer to how loud it sounds)
  setVolume(volume: number): void;
  dispose(): void;
}

export class WallClock implements Clock {
  private at = 0;
  private since = NaN;
  time() {
    return Number.isNaN(this.since) ? this.at : this.at + (performance.now() - this.since) / 1000;
  }
  play() {
    this.since = performance.now();
  }
  pause() {
    this.at = this.time();
    this.since = NaN;
  }
  resume() {
    this.play();
  }
  restart() {
    this.at = 0;
    this.since = NaN;
  }
}

// The folders the file may be in, in order
function audioFolders() {
  const asked = new URLSearchParams(location.search).get("audio");
  return asked ? [asked] : [AUDIO_ROOT, new URL("/build/data/fractals/", location.origin).href];
}

export class FileMusic implements Music {
  readonly kind = "file";
  failed = false;
  private readonly context = new AudioContext({ latencyHint: "playback" });
  private readonly gain = this.context.createGain();
  private buffer?: AudioBuffer;
  private source?: AudioBufferSourceNode;
  // Context time at which film time 0 plays (NaN: not started)
  private startAt = NaN;

  constructor(name: string) {
    this.gain.connect(this.context.destination);
    void this.load(name);
  }

  private async load(name: string) {
    for (const folder of audioFolders()) {
      try {
        const response = await fetch(new URL(`${name}.m4a`, folder));
        if (response.ok) {
          this.buffer = await this.context.decodeAudioData(await response.arrayBuffer());
          return;
        }
      } catch {
        // The next folder
      }
    }
    this.failed = true;
  }

  time() {
    return Number.isNaN(this.startAt) ? 0 : heardTime(this.context) - this.startAt;
  }

  play() {
    if (!this.buffer) {
      return;
    }
    this.source?.stop();
    const source = this.context.createBufferSource();
    source.buffer = this.buffer;
    source.connect(this.gain);
    this.startAt = this.context.currentTime + 0.05;
    source.start(this.startAt);
    this.source = source;
    void this.context.resume();
  }

  pause() {
    void this.context.suspend();
  }

  resume() {
    void this.context.resume();
  }

  restart() {
    this.source?.stop();
    this.source = undefined;
    this.startAt = NaN;
  }

  ready() {
    return Boolean(this.buffer);
  }

  ahead() {
    return this.buffer ? Infinity : 0;
  }

  unlock() {
    void this.context.resume();
  }

  setVolume(volume: number) {
    this.gain.gain.setTargetAtTime(volume * volume, this.context.currentTime, 0.02);
  }

  dispose() {
    this.source?.stop();
    void this.context.close();
  }
}

export class GpuMusic implements Music {
  readonly kind = "gpu";
  readonly failed = false;
  private readonly score: GpuScore;
  private readonly stream: ScoreStream;

  constructor(renderer: WebGPURenderer, duration: number, data: ScoreData) {
    this.score = new GpuScore(renderer, duration, { score: data });
    this.stream = new ScoreStream(this.score);
    this.stream.prepare(0);
  }

  time() {
    return this.stream.clock();
  }

  play() {
    void this.stream.play();
  }

  pause() {
    this.stream.pause();
  }

  resume() {
    this.stream.resume();
  }

  restart() {
    this.stream.restart(0);
  }

  ready(seconds: number) {
    return this.stream.ahead() >= seconds || this.stream.rendered >= this.score.chunks;
  }

  ahead() {
    return this.stream.ahead();
  }

  unlock() {
    void this.stream.context.resume();
  }

  setVolume(volume: number) {
    this.stream.gain.gain.setTargetAtTime(volume * volume, this.stream.context.currentTime, 0.02);
  }

  dispose() {
    this.stream.stop();
    void this.stream.context.close();
    this.score.dispose();
  }
}