All files / blacktrigram/src/audio AudioManager.ts

33.19% Statements 81/244
55.55% Branches 10/18
31.25% Functions 10/32
33.19% Lines 81/244

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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303                1x 1x 6x 6x 6x 6x 6x 6x 6x 6x   1x 6x         6x     1x 2x 2x   1x       1x       1x       1x       1x       1x       1x 6x   6x 6x 6x   6x 6x 6x 6x 6x 6x               6x   1x                     1x 4x   4x 4x                 4x     1x                             1x 2x   2x   2x 2x                       2x   1x 2x           2x   1x                   1x                                           1x             1x             1x                                           1x                                             1x                       1x         1x       1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x   1x 1x 1x 1x   1x         1x       1x       1x       1x     1x   1x  
import {
  AudioAsset,
  AudioConfig,
  IAudioManager,
  MusicTrackId,
  SoundEffectId,
} from "./types";
 
export class AudioManager implements IAudioManager {
  private _masterVolume: number = 1.0;
  private _musicVolume: number = 0.7;
  private _sfxVolume: number = 0.8;
  private _muted: boolean = false;
  private _currentMusicTrack: string | null = null;
  private _fallbackMode: boolean = false;
  private currentMusic: HTMLAudioElement | null = null;
  private soundCache: Map<string, HTMLAudioElement> = new Map();
  private _isInitialized: boolean = false;
 
  constructor(config?: Partial<AudioConfig>) {
    if (config) {
      this._masterVolume = config.masterVolume ?? 1.0;
      this._musicVolume = config.musicVolume ?? 0.7;
      this._sfxVolume = config.sfxVolume ?? 0.8;
    }
  }
 
  // Interface getters
  get isInitialized(): boolean {
    return this._isInitialized;
  }
 
  get fallbackMode(): boolean {
    return this._fallbackMode;
  }
 
  get currentMusicTrack(): string | null {
    return this._currentMusicTrack;
  }
 
  get masterVolume(): number {
    return this._masterVolume;
  }
 
  get sfxVolume(): number {
    return this._sfxVolume;
  }
 
  get musicVolume(): number {
    return this._musicVolume;
  }
 
  get muted(): boolean {
    return this._muted;
  }
 
  async initialize(config?: AudioConfig): Promise<void> {
    try {
      // Remove unused audioContext variable
      new (window.AudioContext || (window as any).webkitAudioContext)();
      this._isInitialized = true;
      this._fallbackMode = false;
 
      if (config) {
        this._masterVolume = config.masterVolume ?? this._masterVolume;
        this._musicVolume = config.musicVolume ?? this._musicVolume;
        this._sfxVolume = config.sfxVolume ?? this._sfxVolume;
      }
    } catch (error) {
      console.warn(
        "AudioContext initialization failed, using fallback mode:",
        error
      );
      this._isInitialized = true;
      this._fallbackMode = true;
    }
  }
 
  async loadAsset(asset: AudioAsset): Promise<void> {
    try {
      const audio = new Audio(asset.url);
      audio.volume = asset.volume || 1.0;
      audio.preload = "auto";
      this.soundCache.set(asset.id, audio);
    } catch (error) {
      console.warn(`Failed to load audio asset ${asset.id}:`, error);
    }
  }
 
  async playSoundEffect(id: SoundEffectId): Promise<void> {
    if (this._muted) return;
 
    const audio = this.soundCache.get(id);
    if (audio) {
      try {
        audio.currentTime = 0;
        audio.volume = this._sfxVolume * this._masterVolume;
        await audio.play();
      } catch (error) {
        console.warn(`Failed to play sound effect ${id}:`, error);
      }
    }
  }
 
  // Alias for playSoundEffect to match interface
  async playSFX(id: SoundEffectId, volume?: number): Promise<void> {
    if (this._muted) return;
 
    const audio = this.soundCache.get(id);
    if (audio) {
      try {
        audio.currentTime = 0;
        audio.volume = (volume ?? this._sfxVolume) * this._masterVolume;
        await audio.play();
      } catch (error) {
        console.warn(`Failed to play sound effect ${id}:`, error);
      }
    }
  }
 
  async playMusic(id: MusicTrackId, volume?: number): Promise<void> {
    if (this._muted) return;
 
    this.stopMusic();
 
    const audio = this.soundCache.get(id);
    if (audio) {
      try {
        audio.currentTime = 0;
        audio.volume = (volume ?? this._musicVolume) * this._masterVolume;
        audio.loop = true;
        this.currentMusic = audio;
        this._currentMusicTrack = id;
        await audio.play();
      } catch (error) {
        console.warn(`Failed to play music ${id}:`, error);
      }
    }
  }
 
  stopMusic(): void {
    if (this.currentMusic) {
      this.currentMusic.pause();
      this.currentMusic.currentTime = 0;
      this.currentMusic = null;
      this._currentMusicTrack = null;
    }
  }
 
  stopAll(): void {
    this.stopMusic();
    this.soundCache.forEach((audio) => {
      if (!audio.paused) {
        audio.pause();
        audio.currentTime = 0;
      }
    });
  }
 
  setVolume(type: "master" | "sfx" | "music" | "voice", volume: number): void {
    const clampedVolume = Math.max(0, Math.min(1, volume));
 
    switch (type) {
      case "master":
        this._masterVolume = clampedVolume;
        break;
      case "sfx":
        this._sfxVolume = clampedVolume;
        break;
      case "music":
        this._musicVolume = clampedVolume;
        if (this.currentMusic) {
          this.currentMusic.volume = this._musicVolume * this._masterVolume;
        }
        break;
      case "voice":
        // Handle voice volume if needed
        break;
    }
  }
 
  mute(): void {
    this._muted = true;
    if (this.currentMusic) {
      this.currentMusic.volume = 0;
    }
  }
 
  unmute(): void {
    this._muted = false;
    if (this.currentMusic) {
      this.currentMusic.volume = this._musicVolume * this._masterVolume;
    }
  }
 
  async fadeOut(duration: number = 1000): Promise<void> {
    if (!this.currentMusic) return;
 
    return new Promise((resolve) => {
      const startVolume = this.currentMusic!.volume;
      const fadeStep = startVolume / (duration / 50);
 
      const fadeInterval = setInterval(() => {
        if (this.currentMusic && this.currentMusic.volume > 0) {
          this.currentMusic.volume = Math.max(
            0,
            this.currentMusic.volume - fadeStep
          );
        } else {
          clearInterval(fadeInterval);
          this.stopMusic();
          resolve();
        }
      }, 50);
    });
  }
 
  async fadeIn(trackId: MusicTrackId, duration: number = 1000): Promise<void> {
    await this.playMusic(trackId, 0);
 
    if (!this.currentMusic) return;
 
    return new Promise((resolve) => {
      const targetVolume = this._musicVolume * this._masterVolume;
      const fadeStep = targetVolume / (duration / 50);
 
      const fadeInterval = setInterval(() => {
        if (this.currentMusic && this.currentMusic.volume < targetVolume) {
          this.currentMusic.volume = Math.min(
            targetVolume,
            this.currentMusic.volume + fadeStep
          );
        } else {
          clearInterval(fadeInterval);
          resolve();
        }
      }, 50);
    });
  }
 
  async crossfade(
    fromTrackId: MusicTrackId,
    toTrackId: MusicTrackId,
    duration: number = 1000
  ): Promise<void> {
    // Fix: Remove unused fromTrackId parameter or use it properly
    const fadeOutPromise = this.fadeOut(duration);
    await fadeOutPromise;
    await this.fadeIn(toTrackId, duration);
    console.log(`Crossfaded from ${fromTrackId} to ${toTrackId}`);
  }
 
  getLoadedAssets(): ReadonlyMap<string, HTMLAudioElement> {
    return new Map(this.soundCache);
  }
 
  // Additional methods to match interface
  async playVoice(id: string): Promise<void> {
    return this.playSoundEffect(id);
  }
 
  async playKoreanTechniqueSound(
    techniqueId: string,
    archetype: string
  ): Promise<void> {
    const soundId = `${archetype}_${techniqueId}`;
    return this.playSoundEffect(soundId);
  }
 
  async playTrigramStanceSound(stance: string): Promise<void> {
    const soundId = `stance_${stance}`;
    return this.playSoundEffect(soundId);
  }
 
  async playVitalPointHitSound(severity: string): Promise<void> {
    const soundId = `vital_point_${severity}`;
    return this.playSoundEffect(soundId);
  }
 
  async playDojiangAmbience(): Promise<void> {
    return this.playMusic("dojang_ambience");
  }
 
  // Legacy getters for backward compatibility
  getMasterVolume(): number {
    return this._masterVolume;
  }
 
  getMusicVolume(): number {
    return this._musicVolume;
  }
 
  getSfxVolume(): number {
    return this._sfxVolume;
  }
 
  get initialized(): boolean {
    return this._isInitialized;
  }
}
 
export default AudioManager;