File size: 4,453 Bytes
f8ca042
 
 
 
 
ac7030c
f8ca042
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac7030c
f8ca042
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5b101c
f8ca042
ac7030c
f8ca042
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use client"

import { useCallback, useEffect, useRef } from "react";
import { create } from "zustand";

import { MediaInfo } from "@/types/general";

// Define the new track type with an optional playNow property
interface PlaybackOptions<T> {
  url: string;
  meta: T;
  isLastTrackOfPlaylist?: boolean;
  playNow?: boolean; // New optional parameter
}

// Define the Zustand store
interface PlaylistState<T> {
  playlist: PlaybackOptions<T>[];
  audio: HTMLAudioElement | null;
  current: T | null;
  interval: NodeJS.Timer | null;
  progress: number;
  setProgress: (progress: number) => void;
  isPlaying: boolean;
  isSwitchingTracks: boolean;
  enqueue: (options: PlaybackOptions<T>) => void;
  dequeue: () => void;
  togglePause: () => void;
}

function getAudio(): HTMLAudioElement | null {
  try {
    return new Audio()
  } catch (err) {
    return null
  }
}

export const usePlaylistStore = create<PlaylistState<MediaInfo>>((set, get) => ({
  playlist: [],
  audio: getAudio(),
  current: null,
  progress: 0,
  interval: null,
  setProgress: (progress) => set((state) => ({
    progress: isNaN(progress) ? 0 : progress,
  })),
  isPlaying: false,
  isSwitchingTracks: false,
  enqueue: (options) => set((state) => ({ playlist: [...state.playlist, options] })),
  dequeue: () => set((state) => {
    const nextPlaying = state.playlist.length > 0 ? state.playlist[0] : null;
    return {
      current: nextPlaying ? nextPlaying.meta : null,
      playlist: state.playlist.slice(1),
      isSwitchingTracks: state.playlist.length > 1,
    };
  }),
  togglePause: () => {
    const { audio, isPlaying } = get()
    // console.log("togglePause: " + isPlaying)
    if (!audio) { return }
    // console.log("doing the thing")

    if (isPlaying) {
      // console.log("we are playing! so setting to false..")
      set({ isPlaying: false });
      audio.pause();
    } else {
      // console.log("we are not playing! so setting to true..")
      set({ isPlaying: true });
      try {
        audio.play()
      } catch (err) {
        console.error("Play failed:", err);
        set({ isPlaying: false });
      }
    }
  }
}));

// The refactored useAudioPlayer hook
export function usePlaylist() {
  const intervalRef = useRef<NodeJS.Timer>();

  const {
    playlist,
    current,
    progress,
    isPlaying,
    isSwitchingTracks,
    enqueue,
    dequeue,
    audio,
    interval,
    setProgress,
    togglePause,
  } = usePlaylistStore();

  const updateProgress = useCallback(() => {
    if (!audio) { return }
    // if (!isPlaying) { return }
    const currentProgress = audio.currentTime / audio.duration;
    // console.log("updateProgress: " + currentProgress)
    setProgress(currentProgress);
    if (currentProgress >= 1) {
      if (!audio.loop) {
        console.log("we reached the end!")
        dequeue();
      }
    }
  }, [audio, audio?.currentTime, dequeue, setProgress, isPlaying]);

  const playback = useCallback(async (options?: PlaybackOptions<MediaInfo>): Promise<void> => {
    if (!audio) { return }

    if (!options) {
      clearInterval(intervalRef.current!);
      // console.log("playback called with nothing, so setting isPlaying to false")
      usePlaylistStore.setState({
        playlist: [],
        current: null,
        isPlaying: false,
        isSwitchingTracks: false
      });
      return
    }

    // console.log("playback!", options)

    if (options.playNow) {
      clearInterval(intervalRef.current!);
      usePlaylistStore.setState({
        playlist: [options as any], // Clears the previous playlist and adds the new track
        current: options.meta,
        isPlaying: true,
        isSwitchingTracks: false
      });

      try {
        audio.pause();
      } catch (err) {}

      try {
        audio.src = options.url;
        audio.load();
      } catch (err) {}

      try {
        await audio.play();
      } catch (err) {
      }
      intervalRef.current = setInterval(updateProgress, 250);
    } else {
      enqueue(options as any);
    }
  }, [enqueue, updateProgress]);

  useEffect(() => {
    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = undefined;
        usePlaylistStore.setState({ interval: null });
      }
      if (audio) {
        audio.pause();
      }
    };
  }, [audio]);

  return { current, playlist, playback, progress, isPlaying, isSwitchingTracks, togglePause };
}