jevstrudel.git / packages / superdough / audioContext.mjs
1/*
2audioContext.mjs - Audio Context manager
3
4Sets up a common and accessible audio context for all superdough operations
5
6Copyright (C) 2025 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/superdough/audiocontext.mjs>
7This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program.  If not, see <https://www.gnu.org/licenses/>.
8*/
9
10import { clearNodePool } from './nodePools.mjs';
11import { ClockBridge } from './clockbridge.mjs';
12
13let audioContext, clockBridge;
14
15export const setDefaultAudioContext = () => {
16  return setAudioContext(new AudioContext());
17};
18
19export const setAudioContext = (context) => {
20  // Existing nodes in the node pool contain references to the previous AudioContext,
21  // so all the nodes in the pool must be cleared when we set a new AudioContext.
22  clearNodePool();
23  if (audioContext && audioContext.state !== 'closed') {
24    audioContext.close();
25  }
26  audioContext = context;
27  clockBridge = new ClockBridge(audioContext);
28  return audioContext;
29};
30
31export const getAudioContext = () => {
32  if (!audioContext) {
33    return setDefaultAudioContext();
34  }
35
36  return audioContext;
37};
38
39export function getClockBridge() {
40  if (!clockBridge) {
41    getAudioContext(); // creates clockBridge
42  }
43  return clockBridge;
44}
45
46export function getAudioContextCurrentTime() {
47  return getAudioContext().currentTime;
48}