File size: 22,242 Bytes
6a03d7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
import type { 
  AudioData, 
  AudioEngine as AudioEngineInterface, 
  Track, 
  PeakDetection, 
  BeatManager, 
  FrequencyMapping 
} from '../types/audio'

export class AudioEngine implements AudioEngineInterface {
  private audioContext: AudioContext | null = null
  private analyser: AnalyserNode | null = null
  private audioElement: HTMLAudioElement | null = null
  private sourceNode: MediaElementAudioSourceNode | null = null
  private isInitialized = false
  private isContextStarted = false
  private currentTrack: Track | null = null
  
  // Auto-play functionality
  private onTrackEndedCallback: (() => void) | null = null
  
  // Audio analysis configuration
  private readonly frequencyMapping: FrequencyMapping = {
    deepFreq: { min: 20, max: 250 },     // Deep Earth Pulse (trunk/roots)
    midFreq: { min: 250, max: 4000 },    // Heartwood Resonance (core glyphs) 
    highFreq: { min: 4000, max: 20000 }  // Canopy Shiver (fractal branches)
  }
  
  private peakDetection: PeakDetection = {
    energyHistory: [],
    historyLength: 30,
    lastPeakTime: 0,
    minTimeBetweenPeaks: 200,
    sensitivity: 1.1
  }
  
  private beatManager: BeatManager = {
    currentWaveRadius: 0,
    waveStrength: 0,
    isWaveActive: false,
    
    triggerWave: (energy: number) => {
      const maxEnergy = 255
      const energyExcess = energy - 200
      this.beatManager.waveStrength = (energyExcess / (maxEnergy - 200)) * 20.0
      this.beatManager.currentWaveRadius = 0
      this.beatManager.isWaveActive = true
    },
    
    update: (deltaTime: number) => {
      if (this.beatManager.isWaveActive) {
        this.beatManager.currentWaveRadius += deltaTime * 1.0
        this.beatManager.waveStrength *= 0.98
        
        if (this.beatManager.currentWaveRadius > 1.0 || this.beatManager.waveStrength < 0.1) {
          this.beatManager.isWaveActive = false
        }
      }
    },
    
    getWaveForce: (distance: number) => {
      if (!this.beatManager.isWaveActive) return 0
      const distanceFromWave = Math.abs(distance - this.beatManager.currentWaveRadius)
      if (distanceFromWave < 0.1) {
        return this.beatManager.waveStrength * Math.exp(-distanceFromWave * 10)
      }
      return 0
    }
  }

  async initialize(): Promise<void> {
    if (this.isInitialized) return

    try {
      // Create AudioContext but don't start it yet (browser security)
      this.audioContext = new (window.AudioContext || (window as any).webkitAudioContext)()
      this.analyser = this.audioContext.createAnalyser()
      this.analyser.fftSize = 2048
      
      // Don't resume context here - wait for user gesture
      this.isInitialized = true
      console.log('AudioEngine initialized (context suspended until user gesture)')
    } catch (error) {
      console.error('Failed to initialize AudioEngine:', error)
      throw error
    }
  }

  private async ensureContextStarted(): Promise<void> {
    if (!this.audioContext || this.isContextStarted) return
    
    if (this.audioContext.state === 'suspended') {
      try {
        await this.audioContext.resume()
        this.isContextStarted = true
        console.log('AudioContext resumed after user gesture')
      } catch (error) {
        console.error('Failed to resume AudioContext:', error)
        throw error
      }
    } else {
      this.isContextStarted = true
    }
  }

  async loadTrack(track: Track): Promise<void> {
    if (!this.isInitialized) {
      throw new Error('AudioEngine not initialized')
    }

    try {
      console.log(`🎡 Loading track: ${track.title} from ${track.url}`)

      // Test if the file is accessible
      console.log('πŸ” Testing file accessibility...')
      try {
        const response = await fetch(track.url, { method: 'HEAD' })
        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`)
        }
        console.log('βœ… File is accessible via HTTP')
        console.log('πŸ“Š Response headers:', {
          contentType: response.headers.get('content-type'),
          contentLength: response.headers.get('content-length'),
          status: response.status
        })
      } catch (fetchError) {
        console.error('❌ File accessibility test failed:', fetchError)
        throw new Error(`Cannot access audio file: ${fetchError}`)
      }

      // Create audio element if it doesn't exist
      if (!this.audioElement) {
        console.log('🎧 Creating new audio element')
        this.audioElement = document.createElement('audio')
        this.audioElement.crossOrigin = 'anonymous'
        this.audioElement.preload = 'metadata'
        this.audioElement.volume = 0.7 // Set initial volume
        
        console.log('πŸ”Š Audio element volume set to:', this.audioElement.volume)
        
        // Add comprehensive event listeners
        this.audioElement.addEventListener('loadedmetadata', () => {
          console.log(`βœ… Track metadata loaded: ${this.audioElement?.duration}s`)
        })
        
        this.audioElement.addEventListener('timeupdate', () => {
          // This enables real-time current time tracking
        })
        
        this.audioElement.addEventListener('ended', () => {
          console.log('πŸ”š Track ended:', this.currentTrack?.title)
          // Trigger auto-play callback if set
          if (this.onTrackEndedCallback) {
            console.log('🎡 Triggering auto-play to next track')
            this.onTrackEndedCallback()
          }
        })
        
        this.audioElement.addEventListener('error', (e) => {
          console.error('❌ Audio error:', e)
          console.error('Error code:', this.audioElement?.error?.code)
          console.error('Error message:', this.audioElement?.error?.message)
        })

        this.audioElement.addEventListener('canplaythrough', () => {
          console.log('βœ… Track can play through')
        })

        this.audioElement.addEventListener('loadstart', () => {
          console.log('πŸ”„ Started loading track')
        })

        this.audioElement.addEventListener('progress', () => {
          console.log('πŸ“Š Loading progress')
        })

        this.audioElement.addEventListener('canplay', () => {
          console.log('βœ… Track can start playing')
        })

        this.audioElement.addEventListener('stalled', () => {
          console.warn('⚠️ Track loading stalled')
        })

        this.audioElement.addEventListener('suspend', () => {
          console.warn('⚠️ Track loading suspended')
        })

        this.audioElement.addEventListener('abort', () => {
          console.warn('⚠️ Track loading aborted')
        })

        console.log('βœ… Audio element created with event listeners')
      }

      // Load the new track
      console.log('πŸ“ Setting audio source...')
      this.audioElement.src = track.url
      this.currentTrack = track

      console.log('πŸ“Š Audio element initial state:', {
        src: this.audioElement.src,
        readyState: this.audioElement.readyState,
        networkState: this.audioElement.networkState
      })

      // Wait for metadata to load
      return new Promise((resolve, reject) => {
        const timeout = setTimeout(() => {
          this.audioElement?.removeEventListener('loadedmetadata', onLoadedMetadata)
          this.audioElement?.removeEventListener('error', onError)
          console.error('❌ Track loading timeout after 10 seconds')
          reject(new Error('Track loading timeout after 10 seconds'))
        }, 10000)

        const onLoadedMetadata = () => {
          clearTimeout(timeout)
          this.audioElement?.removeEventListener('loadedmetadata', onLoadedMetadata)
          this.audioElement?.removeEventListener('error', onError)
          console.log(`βœ… Track loaded successfully: ${track.title}`)
          console.log('πŸ“Š Final audio element state:', {
            duration: this.audioElement?.duration,
            readyState: this.audioElement?.readyState,
            networkState: this.audioElement?.networkState
          })
          resolve()
        }

        const onError = () => {
          clearTimeout(timeout)
          this.audioElement?.removeEventListener('loadedmetadata', onLoadedMetadata)
          this.audioElement?.removeEventListener('error', onError)
          console.error(`❌ Failed to load track: ${track.title}`)
          console.error('❌ Audio element error state:', {
            error: this.audioElement?.error,
            readyState: this.audioElement?.readyState,
            networkState: this.audioElement?.networkState
          })
          reject(new Error('Failed to load audio track'))
        }

        console.log('⏳ Waiting for metadata to load...')
        this.audioElement?.addEventListener('loadedmetadata', onLoadedMetadata)
        this.audioElement?.addEventListener('error', onError)
        this.audioElement?.load()
      })
    } catch (error) {
      console.error('❌ Failed to load track:', error)
      throw error
    }
  }

  async play(): Promise<void> {
    if (!this.audioElement || !this.currentTrack) {
      throw new Error('No track loaded')
    }

    console.log(`🎡 Attempting to play: ${this.currentTrack.title}`)
    console.log(`πŸ“Š Audio element state:`, {
      src: this.audioElement.src,
      readyState: this.audioElement.readyState,
      paused: this.audioElement.paused,
      duration: this.audioElement.duration,
      currentTime: this.audioElement.currentTime,
      volume: this.audioElement.volume
    })

    try {
      // Ensure AudioContext is started (user gesture required)
      await this.ensureContextStarted()

      // Create audio source connection if not already done
      if (!this.sourceNode && this.audioContext && this.analyser && this.isContextStarted) {
        console.log('πŸ”— Connecting audio source to analyser')
        this.sourceNode = this.audioContext.createMediaElementSource(this.audioElement)
        this.sourceNode.connect(this.analyser)
        this.analyser.connect(this.audioContext.destination)
        console.log('βœ… Audio source connected to analyser')
      }

      console.log('▢️ Calling audio.play()')
      await this.audioElement.play()
      console.log('βœ… Playback started successfully')
    } catch (error) {
      console.error('❌ Playback failed:', error)
      if (error instanceof DOMException) {
        console.error('DOMException details:', {
          name: error.name,
          message: error.message,
          code: error.code
        })
      }
      throw error
    }
  }

  pause(): void {
    if (this.audioElement) {
      this.audioElement.pause()
      console.log('Playback paused')
    }
  }

  seekTo(time: number): void {
    if (this.audioElement) {
      this.audioElement.currentTime = time
    }
  }

  setVolume(volume: number): void {
    if (this.audioElement) {
      this.audioElement.volume = Math.max(0, Math.min(1, volume))
    }
  }

  getAudioData(): AudioData {
    if (!this.analyser || !this.audioContext) {
      return {
        frequencies: new Uint8Array(1024),
        deepEnergy: 0,
        midEnergy: 0,
        highEnergy: 0,
        overallAmplitude: 0,
        peakDetected: false,
        beatDetected: false
      }
    }

    try {
      const frequencies = new Uint8Array(this.analyser.frequencyBinCount)
      this.analyser.getByteFrequencyData(frequencies)

      // Convert frequency to array index
      const frequencyToIndex = (frequency: number): number => {
        return Math.round(frequency / (this.audioContext!.sampleRate / 2) * this.analyser!.frequencyBinCount)
      }

      // Extract energy for each frequency range
      const deepIndices = {
        min: frequencyToIndex(this.frequencyMapping.deepFreq.min),
        max: frequencyToIndex(this.frequencyMapping.deepFreq.max)
      }
      const midIndices = {
        min: frequencyToIndex(this.frequencyMapping.midFreq.min), 
        max: frequencyToIndex(this.frequencyMapping.midFreq.max)
      }
      const highIndices = {
        min: frequencyToIndex(this.frequencyMapping.highFreq.min),
        max: frequencyToIndex(this.frequencyMapping.highFreq.max)
      }

      // Calculate normalized energy levels
      const deepRange = frequencies.slice(deepIndices.min, deepIndices.max + 1)
      const midRange = frequencies.slice(midIndices.min, midIndices.max + 1)
      const highRange = frequencies.slice(highIndices.min, highIndices.max + 1)

      const deepEnergy = deepRange.reduce((a, b) => a + b, 0) / deepRange.length / 255
      const midEnergy = midRange.reduce((a, b) => a + b, 0) / midRange.length / 255
      const highEnergy = highRange.reduce((a, b) => a + b, 0) / highRange.length / 255

      // Overall amplitude
      const overallAmplitude = frequencies.reduce((a, b) => a + b, 0) / frequencies.length / 255

      // Peak detection
      const currentEnergy = midEnergy * 255 // Use mid-range for peak detection
      this.peakDetection.energyHistory.push(currentEnergy)
      
      if (this.peakDetection.energyHistory.length > this.peakDetection.historyLength) {
        this.peakDetection.energyHistory.shift()
      }

      const averageEnergy = this.peakDetection.energyHistory.reduce((a, b) => a + b, 0) / 
                           this.peakDetection.energyHistory.length

      const now = performance.now()
      const peakDetected = currentEnergy > averageEnergy * this.peakDetection.sensitivity &&
                          now - this.peakDetection.lastPeakTime > this.peakDetection.minTimeBetweenPeaks

      if (peakDetected) {
        this.peakDetection.lastPeakTime = now
      }

      // Beat detection (based on deep frequencies)
      const beatThreshold = 150 // Normalized threshold
      const beatDetected = deepEnergy * 255 > beatThreshold

      if (beatDetected && !this.beatManager.isWaveActive) {
        this.beatManager.triggerWave(deepEnergy * 255)
      }

      return {
        frequencies,
        deepEnergy,
        midEnergy,
        highEnergy,
        overallAmplitude,
        peakDetected,
        beatDetected
      }

    } catch (error) {
      console.error('Audio analysis failed:', error)
      return {
        frequencies: new Uint8Array(1024),
        deepEnergy: 0,
        midEnergy: 0,
        highEnergy: 0,
        overallAmplitude: 0,
        peakDetected: false,
        beatDetected: false
      }
    }
  }

  // Public method to update beat manager
  updateBeatManager(deltaTime: number): void {
    this.beatManager.update(deltaTime)
  }

  // Public method to get wave force for visualization
  getWaveForce(distance: number): number {
    return this.beatManager.getWaveForce(distance)
  }

  cleanup(): void {
    if (this.sourceNode) {
      this.sourceNode.disconnect()
      this.sourceNode = null
    }
    
    if (this.audioContext) {
      this.audioContext.close()
      this.audioContext = null
    }
    
    if (this.audioElement) {
      this.audioElement.pause()
      this.audioElement.src = ''
      this.audioElement = null
    }
    
    this.analyser = null
    this.isInitialized = false
    
    console.log('AudioEngine cleaned up')
  }

  // New methods for better audio element integration
  getCurrentTime(): number {
    return this.audioElement?.currentTime || 0
  }

  getDuration(): number {
    return this.audioElement?.duration || 0
  }

  getAudioElement(): HTMLAudioElement | null {
    return this.audioElement
  }

  isPlaying(): boolean {
    return this.audioElement ? !this.audioElement.paused : false
  }

  // Test method to verify basic audio functionality
  async testAudioPlayback(url: string): Promise<boolean> {
    console.log('πŸ§ͺ Testing audio file accessibility and format...')
    
    try {
      // First test HTTP accessibility
      const response = await fetch(url, { method: 'HEAD' })
      if (!response.ok) {
        console.error('❌ HTTP test failed:', response.status, response.statusText)
        return false
      }
      
      const contentType = response.headers.get('content-type')
      console.log('πŸ“Š Content-Type:', contentType)
      
      if (!contentType || !contentType.includes('audio/')) {
        console.error('❌ Invalid content type:', contentType)
        return false
      }
      
      // Test audio element loading (without playing to avoid user gesture requirement)
      const testAudio = document.createElement('audio')
      testAudio.volume = 0.1 // Very low volume for safety
      testAudio.src = url
      
      return new Promise((resolve) => {
        const timeout = setTimeout(() => {
          cleanup()
          console.error('❌ Audio test timeout')
          resolve(false)
        }, 5000)
        
        const cleanup = () => {
          clearTimeout(timeout)
          testAudio.removeEventListener('loadedmetadata', onLoadedMetadata)
          testAudio.removeEventListener('error', onError)
          testAudio.src = ''
        }
        
        const onLoadedMetadata = () => {
          console.log('βœ… Audio metadata loaded successfully, duration:', testAudio.duration)
          cleanup()
          resolve(true)
        }
        
        const onError = (e: Event) => {
          console.error('❌ Audio loading error:', e)
          console.error('Error details:', testAudio.error)
          cleanup()
          resolve(false)
        }
        
        testAudio.addEventListener('loadedmetadata', onLoadedMetadata)
        testAudio.addEventListener('error', onError)
        testAudio.load()
      })
    } catch (error) {
      console.error('❌ Audio test failed:', error)
      return false
    }
  }

  // Enhanced frequency analysis for particle systems
  public getAdvancedAudioData(sphere: {
    params: {
      minFrequency: number
      maxFrequency: number
      minFrequencyBeat: number
      maxFrequencyBeat: number
      gainMultiplier: number
      peakSensitivity: number
    }
    peakDetection: {
      energyHistory: number[]
      historyLength: number
      lastPeakTime: number
      minTimeBetweenPeaks: number
    }
  }): {
    average: number
    frequencies: Uint8Array
    peakDetected: boolean
    rangeEnergy: number
    rangeEnergyBeat: number
  } {
    if (!this.analyser || !this.audioContext) {
      return {
        average: 0,
        frequencies: new Uint8Array(),
        peakDetected: false,
        rangeEnergy: 0,
        rangeEnergyBeat: 0
      }
    }

    try {
      const frequencies = new Uint8Array(this.analyser.frequencyBinCount)
      this.analyser.getByteFrequencyData(frequencies)

      // Apply gain multiplier
      const gainMultiplier = sphere.params.gainMultiplier
      frequencies.forEach((value, index) => {
        frequencies[index] = Math.min(value * gainMultiplier, 255)
      })

      // Calculate frequency range indices
      const frequencyToIndex = (frequency: number) => 
        Math.round(frequency / (this.audioContext!.sampleRate / 2) * this.analyser!.frequencyBinCount)

      // Main frequency range for visualization
      const minFreqIndex = frequencyToIndex(sphere.params.minFrequency)
      const maxFreqIndex = frequencyToIndex(sphere.params.maxFrequency)
      const frequencyRange = frequencies.slice(minFreqIndex, maxFreqIndex + 1)
      const rangeEnergy = frequencyRange.reduce((a, b) => a + b, 0) / frequencyRange.length

      // Beat detection frequency range
      const minFreqBeatIndex = frequencyToIndex(sphere.params.minFrequencyBeat)
      const maxFreqBeatIndex = frequencyToIndex(sphere.params.maxFrequencyBeat)
      const frequencyRangeBeat = frequencies.slice(minFreqBeatIndex, maxFreqBeatIndex + 1)
      const rangeEnergyBeat = frequencyRangeBeat.reduce((a, b) => a + b, 0) / frequencyRangeBeat.length

      // Peak detection logic
      sphere.peakDetection.energyHistory.push(rangeEnergy)
      if (sphere.peakDetection.energyHistory.length > sphere.peakDetection.historyLength) {
        sphere.peakDetection.energyHistory.shift()
      }

      const averageEnergy = sphere.peakDetection.energyHistory.reduce((a, b) => a + b, 0) / 
                           sphere.peakDetection.energyHistory.length

      const now = performance.now()
      const peakDetected = rangeEnergy > averageEnergy * sphere.params.peakSensitivity &&
                          now - sphere.peakDetection.lastPeakTime > sphere.peakDetection.minTimeBetweenPeaks

      if (peakDetected) {
        sphere.peakDetection.lastPeakTime = now
        console.log(`🎡 PEAK DETECTED! Energy: ${rangeEnergy.toFixed(1)}, Average: ${averageEnergy.toFixed(1)}`)
      }

      return {
        average: rangeEnergy / 255,
        frequencies,
        peakDetected,
        rangeEnergy,
        rangeEnergyBeat
      }

    } catch (error) {
      console.error('❌ Enhanced audio analysis failed:', error)
      return {
        average: 0,
        frequencies: new Uint8Array(),
        peakDetected: false,
        rangeEnergy: 0,
        rangeEnergyBeat: 0
      }
    }
  }

  // Get smooth volume for rotation effects
  public getSmoothVolume(lastValidVolume: number, volumeChangeThreshold: number): {
    volume: number
    shouldUpdate: boolean
  } {
    if (!this.analyser) {
      return { volume: 0, shouldUpdate: false }
    }

    const bufferLength = this.analyser.frequencyBinCount
    const dataArray = new Uint8Array(bufferLength)
    this.analyser.getByteFrequencyData(dataArray)

    let sum = 0
    for (let i = 0; i < bufferLength; i++) {
      sum += dataArray[i]
    }
    const average = sum / bufferLength
    const normalizedVolume = average / 255

    let shouldUpdate = true
    if (lastValidVolume === 0) {
      lastValidVolume = normalizedVolume
    } else {
      const change = Math.abs(normalizedVolume - lastValidVolume)
      if (change <= volumeChangeThreshold) {
        lastValidVolume = normalizedVolume
      } else {
        shouldUpdate = false
      }
    }

    return { volume: lastValidVolume, shouldUpdate }
  }

  // Auto-play functionality
  public setOnTrackEndedCallback(callback: (() => void) | null): void {
    this.onTrackEndedCallback = callback
    console.log('🎡 Auto-play callback', callback ? 'enabled' : 'disabled')
  }
}