-
Notifications
You must be signed in to change notification settings - Fork 332
/
Copy pathuseAudioPlayer.ts
81 lines (72 loc) · 2.12 KB
/
useAudioPlayer.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
import React, { useCallback } from 'react';
import { NativeHandlers, SoundReturnType } from '../native';
export type UseSoundPlayerProps = {
soundRef: React.MutableRefObject<SoundReturnType | null>;
};
/**
* This hook is used to play, pause, seek and change audio speed.
* It handles both Expo CLI and Native CLI.
*/
export const useAudioPlayer = (props: UseSoundPlayerProps) => {
const { soundRef } = props;
const isExpoCLI = NativeHandlers.SDK === 'stream-chat-expo';
const playAudio = useCallback(async () => {
if (isExpoCLI) {
if (soundRef.current?.playAsync) {
await soundRef.current.playAsync();
}
} else {
if (soundRef.current?.resume) {
soundRef.current.resume();
}
}
}, [isExpoCLI, soundRef]);
const pauseAudio = useCallback(async () => {
if (isExpoCLI) {
if (soundRef.current?.pauseAsync) {
await soundRef.current.pauseAsync();
}
} else {
if (soundRef.current?.pause) {
soundRef.current.pause();
}
}
}, [isExpoCLI, soundRef]);
const seekAudio = useCallback(
async (currentTime: number) => {
if (isExpoCLI) {
if (currentTime === 0) {
// If currentTime is 0, we should replay the video from 0th position.
if (soundRef.current?.replayAsync) {
await soundRef.current.replayAsync({
positionMillis: 0,
shouldPlay: false,
});
}
} else {
if (soundRef.current?.setPositionAsync) {
await soundRef.current.setPositionAsync(currentTime * 1000);
}
}
} else {
if (soundRef.current?.seek) {
soundRef.current.seek(currentTime);
}
}
},
[isExpoCLI, soundRef],
);
const changeAudioSpeed = useCallback(
async (speed: number) => {
// Handled through prop `rate` in `Sound.Player`
if (!isExpoCLI) {
return;
}
if (soundRef.current?.setRateAsync) {
await soundRef.current.setRateAsync(speed);
}
},
[isExpoCLI, soundRef],
);
return { changeAudioSpeed, pauseAudio, playAudio, seekAudio };
};