File size: 2,270 Bytes
503a577
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useEffect, useMemo, useRef, useState } from 'react'
import WaveSurfer from 'wavesurfer.js'
// @ts-ignore: No types for timeline.esm.js
// import Timeline from 'wavesurfer.js/dist/plugins/timeline.esm.js'
import TimelinePlugin from 'wavesurfer.js/dist/plugins/timeline.esm.js'
import API from '../API' // Correct import for the API class

const AudioPlayer = ({ src }: { src: string }) => {
  const containerRef = useRef<HTMLDivElement>(null)
  const wavesurferRef = useRef<WaveSurfer | null>(null)
  const [isPlaying, setIsPlaying] = useState(false)
  // const plugins = useMemo(() => [TimelinePlugin.create()], [])

  const bottomTimeline = TimelinePlugin.create({
    height: 16,
    timeInterval: 0.1,
    primaryLabelInterval: 1,
    style: {
      fontSize: '10px',
      // color: '#6A3274',
    },
  })

  // Initialize WaveSurfer when component mounts
  useEffect(() => {
    if (!containerRef.current) return

    // Get proxied URL to bypass CORS
    const proxiedUrl = API.getProxiedUrl(src)

    // Create an instance of WaveSurfer
    wavesurferRef.current = WaveSurfer.create({
      container: containerRef.current,
      waveColor: 'rgb(200, 0, 200)',
      progressColor: 'rgb(100, 0, 100)',
      url: proxiedUrl, // Use the proxied URL
      minPxPerSec: 100,
      barWidth: 10,
      barRadius: 10,
      barGap: 2,
      mediaControls: true,

      // plugins: [bottomTimeline],
    })

    // Play on click
    wavesurferRef.current.on('interaction', () => {
      wavesurferRef.current?.play()
      setIsPlaying(true)
    })

    // Rewind to the beginning on finished playing
    wavesurferRef.current.on('finish', () => {
      wavesurferRef.current?.setTime(0)
      setIsPlaying(false)
    })

    // Update playing state
    wavesurferRef.current.on('play', () => setIsPlaying(true))
    wavesurferRef.current.on('pause', () => setIsPlaying(false))

    // Cleanup on unmount
    return () => {
      wavesurferRef.current?.destroy()
    }
  }, [src])

  const handlePlayPause = () => {
    wavesurferRef.current?.playPause()
  }

  return (
    <div className="">
      <div ref={containerRef} />
      {/* <button onClick={handlePlayPause}>{isPlaying ? 'Pause' : 'Play'}</button> */}
    </div>
  )
}

export default AudioPlayer