updated to return promise on first click

This commit is contained in:
Jade (Rose) Rowland 2024-05-30 18:52:28 -04:00
parent c0c54c21e3
commit af3d32a493
2 changed files with 16 additions and 14 deletions

View File

@ -64,15 +64,18 @@ export async function initAudio(options = {}) {
}
}
}
let audioReady = false;
export async function initAudioOnFirstClick(options) {
return new Promise((resolve) => {
document.addEventListener('click', async function listener() {
await initAudio(options);
resolve();
document.removeEventListener('click', listener);
if (!audioReady) {
audioReady = new Promise((resolve) => {
document.addEventListener('click', async function listener() {
await initAudio(options);
resolve();
document.removeEventListener('click', listener);
});
});
});
}
return audioReady;
}
let delays = {};

View File

@ -15,6 +15,7 @@ import {
resetGlobalEffects,
resetLoadedSounds,
isAudioInitialized,
initAudioOnFirstClick,
} from '@strudel/webaudio';
import { defaultAudioDeviceName } from '../settings.mjs';
import { getAudioDevices, setAudioDevice } from './util.mjs';
@ -43,8 +44,10 @@ import { getMetadata } from '../metadata_parser';
const { latestCode } = settingsMap.get();
let modulesLoading, presets, drawContext, clearCanvas, isIframe;
let modulesLoading, presets, drawContext, clearCanvas, isIframe, audioReady;
if (typeof window !== 'undefined') {
audioReady = initAudioOnFirstClick();
modulesLoading = loadModules();
presets = prebake();
drawContext = getDrawContext();
@ -83,16 +86,12 @@ export function Repl({ embedded = false }) {
onUpdateState: (state) => {
setReplState({ ...state });
},
onToggle: async (playing) => {
onToggle: (playing) => {
if (!playing) {
clearHydra();
}
},
beforeEval: async () => {
if (!isAudioInitialized()) {
await initAudio();
}
},
beforeEval: () => audioReady,
afterEval: (all) => {
const { code } = all;
setLatestCode(code);