-
Notifications
You must be signed in to change notification settings - Fork 1
/
player.utils.ts
112 lines (101 loc) · 2.87 KB
/
player.utils.ts
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
import {Dispatch, SetStateAction, useEffect, useState} from 'react';
import TrackPlayer, {
Event,
State,
Track,
useProgress,
useTrackPlayerEvents,
} from 'react-native-track-player';
import {songs} from './songs';
export const useInitPlayer = () => {
useEffect(() => {
TrackPlayer.setupPlayer().catch(() => console.log('todo: handle errors'));
return () => {
TrackPlayer.isServiceRunning().then(running => {
if (running) {
return TrackPlayer.reset().catch(() =>
console.log('todo: handle errors'),
);
}
});
};
}, []);
};
export type Controls = {
position: number;
isPlaying: boolean;
duration: number;
startTrack: () => Promise<void>;
skipToNextTrack: () => Promise<void>;
skipToPreviousTrack: () => Promise<void>;
};
export type UsePlayerControlsResponse = {
currentTrack?: Track;
currentTrackIndex?: number;
setCurrentTrack: Dispatch<SetStateAction<Track | undefined>>;
controls: Controls;
};
export const usePlayerControls = (): UsePlayerControlsResponse => {
const [playerState, setPlayerState] = useState<State>();
const [currentTrack, setCurrentTrack] = useState<Track>();
const [currentTrackIndex, setCurrentTrackIndex] = useState<number>();
useEffect(() => {
TrackPlayer.isServiceRunning().then(running => {
if (running && !currentTrack) {
TrackPlayer.getCurrentTrack().then(index => {
if (index != null) {
setCurrentTrackIndex(index);
setCurrentTrack(songs[index]);
}
});
}
});
}, [currentTrack]);
useTrackPlayerEvents(
[Event.PlaybackTrackChanged, Event.PlaybackState],
async event => {
if (
event.type === Event.PlaybackTrackChanged &&
event.nextTrack != null
) {
const track = await TrackPlayer.getTrack(event.nextTrack);
if (track) {
if (track.url !== currentTrack?.url) {
setCurrentTrack(track);
}
if (currentTrackIndex !== event.nextTrack) {
setCurrentTrackIndex(event.nextTrack);
}
}
}
if (event.type === Event.PlaybackState) {
setPlayerState(event.state);
}
},
);
const {position, duration} = useProgress();
const skipToNextTrack = () => TrackPlayer.skipToNext();
const skipToPreviousTrack = () => TrackPlayer.skipToPrevious();
const startTrack = async () => {
const state = await TrackPlayer.getState();
if (state !== State.Playing) {
await TrackPlayer.play();
} else {
await TrackPlayer.pause();
}
};
return {
controls: {
startTrack,
skipToNextTrack,
skipToPreviousTrack,
duration: duration || 25,
isPlaying:
playerState !== State.Playing && playerState !== State.Buffering,
position,
},
currentTrack,
currentTrackIndex,
setCurrentTrack,
};
};