-
Notifications
You must be signed in to change notification settings - Fork 332
/
Copy pathAudioAttachment.tsx
459 lines (433 loc) · 13.2 KB
/
AudioAttachment.tsx
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
import React, { RefObject, useEffect, useMemo, useState } from 'react';
import { I18nManager, Pressable, StyleSheet, Text, View } from 'react-native';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import { useTheme } from '../../contexts';
import { useAudioPlayer } from '../../hooks/useAudioPlayer';
import { Audio, Pause, Play } from '../../icons';
import {
NativeHandlers,
PlaybackStatus,
SoundReturnType,
VideoPayloadData,
VideoProgressData,
VideoSeekResponse,
} from '../../native';
import { FileTypes, type FileUpload } from '../../types/types';
import { getTrimmedAttachmentTitle } from '../../utils/getTrimmedAttachmentTitle';
import { ProgressControl } from '../ProgressControl/ProgressControl';
import { WaveProgressBar } from '../ProgressControl/WaveProgressBar';
dayjs.extend(duration);
export type AudioAttachmentProps = {
item: Omit<FileUpload, 'state'>;
onLoad: (index: string, duration: number) => void;
onPlayPause: (index: string, pausedStatus?: boolean) => void;
onProgress: (index: string, progress: number) => void;
hideProgressBar?: boolean;
showSpeedSettings?: boolean;
testID?: string;
};
/**
* AudioAttachment
* UI Component to preview the audio files
*/
export const AudioAttachment = (props: AudioAttachmentProps) => {
const [currentSpeed, setCurrentSpeed] = useState<number>(1.0);
const [audioFinished, setAudioFinished] = useState(false);
const soundRef = React.useRef<SoundReturnType | null>(null);
const {
hideProgressBar = false,
item,
onLoad,
onPlayPause,
onProgress,
showSpeedSettings = false,
testID,
} = props;
const { changeAudioSpeed, pauseAudio, playAudio, seekAudio } = useAudioPlayer({ soundRef });
const isExpoCLI = NativeHandlers.SDK === 'stream-chat-expo';
const isVoiceRecording = item.type === FileTypes.VoiceRecording;
/** This is for Native CLI Apps */
const handleLoad = (payload: VideoPayloadData) => {
// The duration given by the rn-video is not same as the one of the voice recording, so we take the actual duration for voice recording.
if (isVoiceRecording && item.duration) {
onLoad(item.id, item.duration);
} else {
onLoad(item.id, item.duration || payload.duration);
}
};
/** This is for Native CLI Apps */
const handleProgress = (data: VideoProgressData) => {
const { currentTime, seekableDuration } = data;
// The duration given by the rn-video is not same as the one of the voice recording, so we take the actual duration for voice recording.
if (isVoiceRecording && item.duration) {
if (currentTime < item.duration && !audioFinished) {
onProgress(item.id, currentTime / item.duration);
} else {
setAudioFinished(true);
}
} else {
if (currentTime < seekableDuration && !audioFinished) {
onProgress(item.id, currentTime / seekableDuration);
} else {
setAudioFinished(true);
}
}
};
/** This is for Native CLI Apps */
const onSeek = (seekResponse: VideoSeekResponse) => {
setAudioFinished(false);
onProgress(item.id, seekResponse.currentTime / (item.duration as number));
};
const handlePlayPause = async () => {
if (item.paused) {
if (isExpoCLI) {
await playAudio();
}
onPlayPause(item.id, false);
} else {
if (isExpoCLI) {
await pauseAudio();
}
onPlayPause(item.id, true);
}
};
const handleEnd = async () => {
setAudioFinished(false);
await pauseAudio();
onPlayPause(item.id, true);
await seekAudio(0);
};
const dragStart = async () => {
if (isExpoCLI) {
await pauseAudio();
}
onPlayPause(item.id, true);
};
const dragProgress = (progress: number) => {
onProgress(item.id, progress);
};
const dragEnd = async (progress: number) => {
await seekAudio(progress * (item.duration as number));
if (isExpoCLI) {
await playAudio();
}
onPlayPause(item.id, false);
};
/** For Expo CLI */
const onPlaybackStatusUpdate = (playbackStatus: PlaybackStatus) => {
if (!playbackStatus.isLoaded) {
// Update your UI for the unloaded state
if (playbackStatus.error) {
console.log(`Encountered a fatal error during playback: ${playbackStatus.error}`);
}
} else {
const { durationMillis, positionMillis } = playbackStatus;
// This is done for Expo CLI where we don't get file duration from file picker
if (item.duration === 0) {
onLoad(item.id, durationMillis / 1000);
} else {
// The duration given by the expo-av is not same as the one of the voice recording, so we take the actual duration for voice recording.
if (isVoiceRecording && item.duration) {
onLoad(item.id, item.duration);
} else {
onLoad(item.id, durationMillis / 1000);
}
}
// Update your UI for the loaded state
if (playbackStatus.isPlaying) {
if (isVoiceRecording && item.duration) {
if (positionMillis <= item.duration * 1000) {
onProgress(item.id, positionMillis / (item.duration * 1000));
}
} else {
if (positionMillis <= durationMillis) {
onProgress(item.id, positionMillis / durationMillis);
}
}
} else {
// Update your UI for the paused state
}
if (playbackStatus.isBuffering) {
// Update your UI for the buffering state
}
if (playbackStatus.didJustFinish && !playbackStatus.isLooping) {
onProgress(item.id, 1);
// The player has just finished playing and will stop. Maybe you want to play something else?
// status: opposite of pause,says i am playing
handleEnd();
}
}
};
// This is for Expo CLI, sound initialization is done here.
useEffect(() => {
if (isExpoCLI) {
const initiateSound = async () => {
if (item && item.file && item.file.uri && NativeHandlers.Sound?.initializeSound) {
soundRef.current = await NativeHandlers.Sound.initializeSound(
{ uri: item.file.uri },
{
progressUpdateIntervalMillis: 100,
},
onPlaybackStatusUpdate,
);
}
};
initiateSound();
}
return () => {
if (soundRef.current?.stopAsync && soundRef.current.unloadAsync) {
soundRef.current.stopAsync();
soundRef.current.unloadAsync();
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// This is needed for expo applications where the rerender doesn't occur on time thefore you need to update the state of the sound.
useEffect(() => {
const initalPlayPause = async () => {
if (!isExpoCLI) {
return;
}
try {
if (item.paused) {
await pauseAudio();
} else {
await playAudio();
}
} catch (e) {
console.log('An error has occurred while trying to interact with the audio. ', e);
}
};
// For expo CLI
if (!NativeHandlers.Sound?.Player) {
initalPlayPause();
}
}, [item.paused, isExpoCLI, pauseAudio, playAudio]);
const onSpeedChangeHandler = async () => {
if (currentSpeed === 2.0) {
setCurrentSpeed(1.0);
await changeAudioSpeed(1.0);
} else {
if (currentSpeed === 1.0) {
setCurrentSpeed(1.5);
await changeAudioSpeed(1.5);
} else if (currentSpeed === 1.5) {
setCurrentSpeed(2.0);
await changeAudioSpeed(2.0);
}
}
};
const {
theme: {
audioAttachment: {
container,
leftContainer,
playPauseButton,
progressControlContainer,
progressDurationText,
rightContainer,
speedChangeButton,
speedChangeButtonText,
},
colors: { accent_blue, black, grey_dark, grey_whisper, static_black, static_white, white },
messageInput: {
fileUploadPreview: { filenameText },
},
},
} = useTheme();
const progressValueInSeconds = useMemo(
() => (item.duration as number) * (item.progress as number),
[item.duration, item.progress],
);
const progressDuration = useMemo(
() =>
progressValueInSeconds
? progressValueInSeconds / 3600 >= 1
? dayjs.duration(progressValueInSeconds, 'second').format('HH:mm:ss')
: dayjs.duration(progressValueInSeconds, 'second').format('mm:ss')
: dayjs.duration(item.duration ?? 0, 'second').format('mm:ss'),
[progressValueInSeconds, item.duration],
);
return (
<View
accessibilityLabel='audio-attachment-preview'
style={[
styles.container,
{
backgroundColor: white,
borderColor: grey_whisper,
},
container,
]}
testID={testID}
>
<View style={[styles.leftContainer, leftContainer]}>
<Pressable
accessibilityLabel='Play Pause Button'
onPress={handlePlayPause}
style={[
styles.playPauseButton,
{ backgroundColor: static_white, shadowColor: black },
playPauseButton,
]}
>
{item.paused ? (
<Play fill={static_black} height={32} width={32} />
) : (
<Pause fill={static_black} height={32} width={32} />
)}
</Pressable>
</View>
<View style={[styles.centerContainer]}>
<Text
accessibilityLabel='File Name'
numberOfLines={1}
style={[
styles.filenameText,
{
color: black,
},
I18nManager.isRTL ? { writingDirection: 'rtl' } : { writingDirection: 'ltr' },
filenameText,
]}
>
{getTrimmedAttachmentTitle(item.file.name)}
</Text>
<View style={styles.audioInfo}>
<Text style={[styles.progressDurationText, { color: grey_dark }, progressDurationText]}>
{progressDuration}
</Text>
{!hideProgressBar && (
<View style={[styles.progressControlContainer, progressControlContainer]}>
{item.file.waveform_data ? (
<WaveProgressBar
amplitudesCount={30}
onEndDrag={dragEnd}
onProgressDrag={dragProgress}
onStartDrag={dragStart}
progress={item.progress as number}
waveformData={item.file.waveform_data}
/>
) : (
<ProgressControl
duration={item.duration as number}
filledColor={accent_blue}
onEndDrag={dragEnd}
onProgressDrag={dragProgress}
onStartDrag={dragStart}
progress={item.progress as number}
testID='progress-control'
/>
)}
</View>
)}
</View>
{NativeHandlers.Sound?.Player && (
<NativeHandlers.Sound.Player
onEnd={handleEnd}
onLoad={handleLoad}
onProgress={handleProgress}
onSeek={onSeek}
paused={item.paused}
rate={currentSpeed}
soundRef={soundRef as RefObject<SoundReturnType>}
testID='sound-player'
uri={item.file.uri}
/>
)}
</View>
{showSpeedSettings ? (
<View style={[styles.rightContainer, rightContainer]}>
{item.paused ? (
<Audio fill={'#ffffff'} />
) : (
<Pressable
onPress={onSpeedChangeHandler}
style={[
styles.speedChangeButton,
{ backgroundColor: static_white, shadowColor: black },
speedChangeButton,
]}
>
<Text
style={[styles.speedChangeButtonText, speedChangeButtonText]}
>{`x${currentSpeed.toFixed(1)}`}</Text>
</Pressable>
)}
</View>
) : null}
</View>
);
};
const styles = StyleSheet.create({
audioInfo: {
alignItems: 'center',
flexDirection: 'row',
},
centerContainer: {
flexGrow: 1,
},
container: {
alignItems: 'center',
borderRadius: 12,
borderWidth: 1,
flex: 1,
flexDirection: 'row',
paddingLeft: 8,
paddingRight: 16,
paddingVertical: 12,
},
filenameText: {
fontSize: 14,
fontWeight: 'bold',
marginBottom: 8,
},
leftContainer: {
marginRight: 8,
},
playPauseButton: {
alignItems: 'center',
borderRadius: 50,
elevation: 4,
justifyContent: 'center',
marginRight: 8,
padding: 4,
shadowOffset: {
height: 2,
width: 0,
},
shadowOpacity: 0.23,
shadowRadius: 2.62,
},
progressControlContainer: {
flexGrow: 1,
justifyContent: 'center',
},
progressDurationText: {
fontSize: 12,
marginRight: 8,
},
rightContainer: {
marginLeft: 16,
},
speedChangeButton: {
alignItems: 'center',
alignSelf: 'center',
borderRadius: 50,
elevation: 4,
justifyContent: 'center',
paddingHorizontal: 8,
paddingVertical: 4,
shadowOffset: {
height: 2,
width: 0,
},
shadowOpacity: 0.23,
shadowRadius: 2.62,
},
speedChangeButtonText: {
fontSize: 12,
},
});
AudioAttachment.displayName = 'AudioAttachment{messageInput{audioAttachment}}';