From da70a4ce7eafef5e9efbe28dd30d84178b773a33 Mon Sep 17 00:00:00 2001 From: JellyBrick Date: Tue, 28 Nov 2023 12:11:48 +0900 Subject: [PATCH] fix: fix `audioCanPlay` event - e.g. Visualizer Plugin --- src/renderer.ts | 57 +++++++++++++++++++++++++++---------------------- 1 file changed, 32 insertions(+), 25 deletions(-) diff --git a/src/renderer.ts b/src/renderer.ts index ba6d6b78..c70db501 100644 --- a/src/renderer.ts +++ b/src/renderer.ts @@ -41,7 +41,7 @@ interface YouTubeMusicAppElement extends HTMLElement { navigate_(page: string): void; } -function onApiLoaded() { +async function onApiLoaded() { window.ipcRenderer.on('seekTo', (_, t: number) => api!.seekTo(t)); window.ipcRenderer.on('seekBy', (_, t: number) => api!.seekBy(t)); @@ -53,35 +53,42 @@ function onApiLoaded() { const audioSource = audioContext.createMediaElementSource(video); audioSource.connect(audioContext.destination); + for (const [id, plugin] of Object.entries(getAllLoadedRendererPlugins())) { + if (typeof plugin.renderer !== 'function') { + await plugin.renderer?.onPlayerApiReady?.bind(plugin.renderer)?.(api!, createContext(id)); + } + } + + const audioCanPlayEventDispatcher = () => { + document.dispatchEvent( + new CustomEvent('audioCanPlay', { + detail: { + audioContext, + audioSource, + }, + }), + ); + }; + + const loadstartListener = () => { + // Emit "audioCanPlay" for each video + video.addEventListener( + 'canplaythrough', + audioCanPlayEventDispatcher, + { once: true }, + ); + }; + + if (video.readyState === 4 /* HAVE_ENOUGH_DATA (loaded) */) { + audioCanPlayEventDispatcher(); + } + video.addEventListener( 'loadstart', - () => { - // Emit "audioCanPlay" for each video - video.addEventListener( - 'canplaythrough', - () => { - document.dispatchEvent( - new CustomEvent('audioCanPlay', { - detail: { - audioContext, - audioSource, - }, - }), - ); - }, - { once: true }, - ); - }, + loadstartListener, { passive: true }, ); - Object.entries(getAllLoadedRendererPlugins()) - .forEach(([id, plugin]) => { - if (typeof plugin.renderer !== 'function') { - plugin.renderer?.onPlayerApiReady?.bind(plugin.renderer)?.(api!, createContext(id)); - } - }); - window.ipcRenderer.send('ytmd:player-api-loaded'); // Navigate to "Starting page"