All files / audio AudioProvider.tsx

81.81% Statements 54/66
72.72% Branches 8/11
77.77% Functions 21/27
82.81% Lines 53/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239                                                                          10x   10x 185x 185x 185x     10x           158x 104x   158x       158x                 158x 2x                 158x       100x 100x     100x 100x   4900x             100x               100x 500x   100x   500x             100x 100x 100x           100x 500x   100x 500x 500x     500x     100x 500x   100x   500x           100x                 158x 104x 98x       158x   157x               157x 2x 2x     157x             157x                                             28x     3x     73x     73x     158x                             158x            
import React, {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useState,
} from "react";
import { ARCHETYPE_ASSETS } from "../types/constants";
import { audioAssetRegistry } from "./AudioAssetRegistry";
import AudioManager from "./AudioManager";
import placeholderAssets from "./placeholder-sounds";
import { AudioAsset, AudioConfig, IAudioManager } from "./types";
 
export interface AudioProviderProps {
  children: React.ReactNode;
  config?: Partial<AudioConfig>;
  manager?: IAudioManager;
  /**
   * If true, defers audio initialization until initializeAudio() is called.
   * This is useful for requiring user gesture before creating AudioContext.
   */
  deferInitialization?: boolean;
}
 
export interface AudioContextValue extends IAudioManager {
  /**
   * Initialize audio manager. Must be called after user gesture if deferInitialization is true.
   */
  initializeAudio: () => Promise<void>;
  /**
   * Whether audio system has been fully initialized and is ready for use.
   * This includes both AudioContext creation (isInitialized) and asset preloading.
   * Use this property to determine if audio methods can be safely called.
   */
  isAudioReady: boolean;
}
 
export const AudioContext = createContext<AudioContextValue | null>(null);
 
export const useAudio = (): AudioContextValue => {
  const ctx = useContext(AudioContext);
  Iif (!ctx) throw new Error("useAudio must be inside AudioProvider");
  return ctx;
};
 
export const AudioProvider: React.FC<AudioProviderProps> = ({
  children,
  config,
  manager,
  deferInitialization = false,
}) => {
  const [audioManager] = useState<IAudioManager>(
    () => manager ?? new AudioManager(config)
  );
  const [isAudioReady, setIsAudioReady] = useState(false);
 
  // Track volume states explicitly to trigger re-renders when they change
  // Initialize with audioManager values to sync with any custom manager
  const [volumeState, setVolumeState] = useState(() => ({
    masterVolume: audioManager.masterVolume,
    sfxVolume: audioManager.sfxVolume,
    musicVolume: audioManager.musicVolume,
    muted: audioManager.muted,
    isInitialized: audioManager.isInitialized,
  }));
 
  // Update volume state whenever audioManager values change
  const syncVolumeState = useCallback(() => {
    setVolumeState({
      masterVolume: audioManager.masterVolume,
      sfxVolume: audioManager.sfxVolume,
      musicVolume: audioManager.musicVolume,
      muted: audioManager.muted,
      isInitialized: audioManager.isInitialized,
    });
  }, [audioManager]);
 
  const initializeAudio = useCallback(async () => {
    // Note: We don't check isAudioReady here to allow retry attempts
    // If initialization fails, users can retry by calling this again
 
    try {
      await audioManager.initialize(); // no args
 
      // Preload all placeholder assets
      const list = Object.values(placeholderAssets).flat() as AudioAsset[];
      await Promise.all(
        list.map((a) =>
          audioManager.loadAsset(a).catch((err) => {
            console.warn(`Failed to load placeholder asset: ${a.id}`, err);
          })
        )
      );
 
      // Preload menu UI sounds from registry (critical for intro screen)
      const menuSounds = [
        audioAssetRegistry.getSFX("menu_hover"),
        audioAssetRegistry.getSFX("menu_select"),
        audioAssetRegistry.getSFX("menu_click"),
        audioAssetRegistry.getSFX("menu_navigate"),
        audioAssetRegistry.getSFX("menu_back"),
      ];
 
      const menuAssets = menuSounds.filter(
        (asset) => asset !== undefined
      ) as AudioAsset[];
      await Promise.all(
        menuAssets.map((a) =>
          audioManager.loadAsset(a).catch((err) => {
            console.warn(`Failed to load menu asset: ${a.id}`, err);
          })
        )
      );
 
      // Preload intro music
      const introMusic = audioAssetRegistry.getMusic("intro_theme");
      Eif (introMusic) {
        await audioManager.loadAsset(introMusic as AudioAsset).catch((err) => {
          console.warn("Failed to load intro theme music", err);
        });
      }
 
      // Preload archetype theme music for character selection
      const archetypeThemeIds = Object.values(ARCHETYPE_ASSETS).map(
        (a) => a.themeId
      );
      const archetypeThemes = archetypeThemeIds.map((id) => {
        const track = audioAssetRegistry.getMusic(id);
        Iif (!track) {
          console.warn(`Archetype theme not registered: ${id}`);
        }
        return track;
      });
 
      const archetypeAssets = archetypeThemes.filter(
        (asset) => asset !== undefined
      ) as AudioAsset[];
      await Promise.all(
        archetypeAssets.map((a) =>
          audioManager.loadAsset(a).catch((err) => {
            console.warn(`Failed to load archetype theme: ${a.id}`, err);
          })
        )
      );
 
      setIsAudioReady(true);
    } catch (error) {
      console.error("Failed to initialize audio manager:", error);
      // Continue without audio - silent mode fallback
      setIsAudioReady(true); // Mark as ready even in fallback mode
    }
  }, [audioManager]); // Removed isAudioReady to prevent unnecessary callback recreation
 
  // Auto-initialize if not deferred
  useEffect(() => {
    if (!deferInitialization) {
      initializeAudio();
    }
  }, [deferInitialization, initializeAudio]);
 
  const contextValue = React.useMemo<AudioContextValue>(() => {
    // Wrap methods that change volume state to also sync React state
    const wrappedSetVolume = (
      type: "master" | "sfx" | "music" | "voice",
      volume: number
    ) => {
      audioManager.setVolume(type, volume);
      syncVolumeState();
    };
 
    const wrappedMute = () => {
      audioManager.mute();
      syncVolumeState();
    };
 
    const wrappedUnmute = () => {
      audioManager.unmute();
      syncVolumeState();
    };
 
    // Create a dynamic wrapper that accesses getter properties on-demand
    // This ensures components always get current values
    return {
      // Explicitly bind all IAudioManager methods
      initialize: audioManager.initialize.bind(audioManager),
      loadAsset: audioManager.loadAsset.bind(audioManager),
      playSFX: audioManager.playSFX.bind(audioManager),
      playSoundEffect: audioManager.playSoundEffect.bind(audioManager),
      playMusic: audioManager.playMusic.bind(audioManager),
      stopMusic: audioManager.stopMusic.bind(audioManager),
      setVolume: wrappedSetVolume,
      mute: wrappedMute,
      unmute: wrappedUnmute,
      fadeIn: audioManager.fadeIn.bind(audioManager),
      fadeOut: audioManager.fadeOut.bind(audioManager),
      playKoreanTechniqueSound:
        audioManager.playKoreanTechniqueSound.bind(audioManager),
      playTrigramStanceSound:
        audioManager.playTrigramStanceSound.bind(audioManager),
      playVitalPointHitSound:
        audioManager.playVitalPointHitSound.bind(audioManager),
      playDojiangAmbience: audioManager.playDojiangAmbience.bind(audioManager),
 
      // Use tracked state values for reactivity (triggers re-renders)
      get isInitialized() {
        return volumeState.isInitialized;
      },
      get masterVolume() {
        return volumeState.masterVolume;
      },
      get sfxVolume() {
        return volumeState.sfxVolume;
      },
      get musicVolume() {
        return volumeState.musicVolume;
      },
      get muted() {
        return volumeState.muted;
      },
 
      // AudioProvider-specific properties
      initializeAudio,
      isAudioReady,
    };
  }, [
    audioManager,
    initializeAudio,
    isAudioReady,
    syncVolumeState,
    volumeState,
  ]);
 
  return (
    <AudioContext.Provider value={contextValue}>
      {children}
    </AudioContext.Provider>
  );
};