-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathApp.tsx
More file actions
428 lines (399 loc) · 12.4 KB
/
App.tsx
File metadata and controls
428 lines (399 loc) · 12.4 KB
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
import {
FinishMode,
IWaveformRef,
PermissionStatus,
PlaybackSpeedType,
PlayerState,
RecorderState,
UpdateFrequency,
Waveform,
useAudioPermission,
useAudioPlayer,
} from '@simform_solutions/react-native-audio-waveform';
import React, {
Dispatch,
SetStateAction,
useEffect,
useRef,
useState,
} from 'react';
import {
ActivityIndicator,
Alert,
Image,
Linking,
Pressable,
ScrollView,
StatusBar,
Text,
View,
} from 'react-native';
import fs from 'react-native-fs';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import {
SafeAreaProvider,
useSafeAreaInsets,
} from 'react-native-safe-area-context';
import { Icons } from './assets';
import {
generateAudioList,
getRecordedAudios,
playbackSpeedSequence,
type ListItem,
} from './constants';
import stylesheet from './styles';
import { Colors } from './theme';
let currentPlayingRef: React.RefObject<IWaveformRef> | undefined;
const RenderListItem = React.memo(
({
item,
onPanStateChange,
currentPlaybackSpeed,
changeSpeed,
}: {
item: ListItem;
onPanStateChange: (value: boolean) => void;
currentPlaybackSpeed: PlaybackSpeedType;
changeSpeed: () => void;
}) => {
const ref = useRef<IWaveformRef>(null);
const [playerState, setPlayerState] = useState(PlayerState.stopped);
const styles = stylesheet({ currentUser: item.fromCurrentUser });
const [isLoading, setIsLoading] = useState(true);
const handlePlayPauseAction = async () => {
// If we are recording do nothing
if (
currentPlayingRef?.current?.currentState === RecorderState.recording
) {
return;
}
const startNewPlayer = async () => {
currentPlayingRef = ref;
if (ref.current?.currentState === PlayerState.paused) {
await ref.current?.resumePlayer();
} else {
await ref.current?.startPlayer({
finishMode: FinishMode.stop,
});
// If the player took too much time to initialize and another player started instead we pause the former one!
if (
currentPlayingRef?.current?.playerKey !== ref?.current?.playerKey
) {
await ref?.current?.pausePlayer();
}
}
};
// If no player or if current player is stopped just start the new player!
if (
currentPlayingRef == null ||
[PlayerState.stopped, PlayerState.paused].includes(
currentPlayingRef?.current?.currentState as PlayerState
)
) {
await startNewPlayer();
} else {
// Pause current player if it was playing
if (currentPlayingRef?.current?.currentState === PlayerState.playing) {
await currentPlayingRef?.current?.pausePlayer();
}
// Start player when it is a different one!
if (currentPlayingRef?.current?.playerKey !== ref?.current?.playerKey) {
await startNewPlayer();
}
}
};
const handleStopAction = async () => {
ref.current?.stopPlayer();
};
return (
<View key={item.path} style={[styles.listItemContainer]}>
<View style={styles.listItemWidth}>
<View style={[styles.buttonContainer]}>
<Pressable
disabled={isLoading}
onPress={handlePlayPauseAction}
style={styles.playBackControlPressable}>
{isLoading ? (
<ActivityIndicator color={'#FFFFFF'} />
) : (
<Image
source={
playerState !== PlayerState.playing
? Icons.play
: Icons.pause
}
style={styles.buttonImage}
resizeMode="contain"
/>
)}
</Pressable>
<Pressable
disabled={PlayerState.stopped == playerState}
onPress={handleStopAction}
style={styles.playBackControlPressable}>
<Image
source={Icons.stop}
style={[
styles.stopButton,
{
opacity: playerState === PlayerState.stopped ? 0.5 : 1,
},
]}
resizeMode="contain"
/>
</Pressable>
<Waveform
containerStyle={styles.staticWaveformView}
mode="static"
key={item.path}
playbackSpeed={currentPlaybackSpeed}
ref={ref}
path={item.path}
candleSpace={2}
candleWidth={4}
scrubColor={Colors.white}
waveColor={Colors.lightWhite}
candleHeightScale={4}
onPlayerStateChange={setPlayerState}
onPanStateChange={onPanStateChange}
onError={error => {
console.log('Error in static player:', error);
}}
onCurrentProgressChange={(_currentProgress, _songDuration) => {
// console.log(
// `currentProgress ${currentProgress}, songDuration ${songDuration}`
// );
}}
onChangeWaveformLoadState={state => {
setIsLoading(state);
}}
/>
{playerState === PlayerState.playing ? (
<Pressable
onPress={changeSpeed}
style={[styles.speedBox, styles.whiteBackground]}>
<Text style={styles.speed}>{`${currentPlaybackSpeed}x`}</Text>
</Pressable>
) : (
<Image style={styles.speedBox} source={Icons.logo} />
)}
</View>
</View>
</View>
);
}
);
const LivePlayerComponent = ({
setList,
}: {
setList: Dispatch<SetStateAction<ListItem[]>>;
}) => {
const ref = useRef<IWaveformRef>(null);
const [recorderState, setRecorderState] = useState(RecorderState.stopped);
const styles = stylesheet();
const { checkHasAudioRecorderPermission, getAudioRecorderPermission } =
useAudioPermission();
const startRecording = () => {
ref.current
?.startRecord({
updateFrequency: UpdateFrequency.high,
})
.then(() => {})
.catch(() => {});
};
const handleRecorderAction = async () => {
if (recorderState === RecorderState.stopped) {
// Stopping other player before starting recording
if (currentPlayingRef?.current?.currentState === PlayerState.playing) {
currentPlayingRef?.current?.stopPlayer();
}
const hasPermission = await checkHasAudioRecorderPermission();
if (hasPermission === PermissionStatus.granted) {
currentPlayingRef = ref;
startRecording();
} else if (hasPermission === PermissionStatus.undetermined) {
const permissionStatus = await getAudioRecorderPermission();
if (permissionStatus === PermissionStatus.granted) {
currentPlayingRef = ref;
startRecording();
}
} else {
Linking.openSettings();
}
} else {
ref.current?.stopRecord().then(path => {
setList(prev => [...prev, { fromCurrentUser: true, path }]);
});
currentPlayingRef = undefined;
}
};
return (
<View style={styles.liveWaveformContainer}>
<Waveform
mode="live"
containerStyle={styles.liveWaveformView}
ref={ref}
candleSpace={2}
candleWidth={4}
waveColor={Colors.pink}
onRecorderStateChange={setRecorderState}
/>
<Pressable
onPress={handleRecorderAction}
style={styles.recordAudioPressable}>
<Image
source={
recorderState === RecorderState.stopped ? Icons.mic : Icons.stop
}
style={styles.buttonImageLive}
resizeMode="contain"
/>
</Pressable>
</View>
);
};
const AppContainer = () => {
const [shouldScroll, setShouldScroll] = useState<boolean>(true);
const [list, setList] = useState<ListItem[]>([]);
const [nbOfRecording, setNumberOfRecording] = useState<number>(0);
const [currentPlaybackSpeed, setCurrentPlaybackSpeed] =
useState<PlaybackSpeedType>(1.0);
const { top, bottom } = useSafeAreaInsets();
const styles = stylesheet({ top, bottom });
useEffect(() => {
generateAudioList().then(audioListArray => {
if (audioListArray?.length > 0) {
setList(audioListArray);
}
});
}, []);
useEffect(() => {
getRecordedAudios().then(recordedAudios =>
setNumberOfRecording(recordedAudios.length)
);
}, [list]);
const changeSpeed = () => {
setCurrentPlaybackSpeed(
prev =>
playbackSpeedSequence[
(playbackSpeedSequence.indexOf(prev) + 1) %
playbackSpeedSequence.length
] ?? 1.0
);
};
const handleDeleteRecordings = async () => {
const recordings = await getRecordedAudios();
const deleteRecordings = async () => {
await Promise.all(recordings.map(async recording => fs.unlink(recording)))
.then(() => {
generateAudioList().then(audioListArray => {
setList(audioListArray);
});
})
.catch(error => {
Alert.alert(
'Error deleting recordings',
'Below error happened while deleting recordings:\n' + error,
[{ text: 'Dismiss' }]
);
});
};
Alert.alert(
'Delete all recording',
`Continue to delete all ${recordings.length} recordings.`,
[
{ text: 'Cancel', style: 'cancel' },
{ text: 'OK', onPress: deleteRecordings },
]
);
};
const handleStopPlayersAndExtractors = async () => {
await currentPlayingRef?.current?.stopPlayer();
const { stopPlayersAndExtractors } = useAudioPlayer();
const hasStoppedAll: boolean[] = await stopPlayersAndExtractors();
if (hasStoppedAll.every(Boolean)) {
Alert.alert(
'Everything stopped',
'All players and extractors have been stopped!',
[{ text: 'OK' }]
);
} else {
Alert.alert(
'Error stopping everything',
'An error occurred when trying to stop players or extractors',
[{ text: 'OK' }]
);
}
};
return (
<View style={styles.appContainer}>
<StatusBar
barStyle={'dark-content'}
backgroundColor={'transparent'}
animated
translucent
/>
<GestureHandlerRootView style={styles.appContainer}>
<View style={styles.screenBackground}>
<View style={styles.container}>
<View style={styles.simformImageContainer}>
<Image
source={Icons.simform}
style={styles.simformImage}
resizeMode="contain"
/>
</View>
<View style={styles.advancedOptionsContainer}>
<Pressable
style={[
styles.advancedOptionItem,
{ opacity: nbOfRecording ? 1 : 0.5 },
]}
onPress={handleDeleteRecordings}
disabled={!nbOfRecording}>
<Image
source={Icons.delete}
style={styles.pinkButtonImage}
resizeMode="contain"
/>
<Text style={styles.advancedOptionItemTitle}>
{'Delete recorded audio files'}
</Text>
</Pressable>
<Pressable
style={styles.advancedOptionItem}
onPress={handleStopPlayersAndExtractors}>
<Image
source={Icons.stop}
style={[styles.pinkButtonImage]}
resizeMode="contain"
/>
<Text style={styles.advancedOptionItemTitle}>
{'Stop all players and extractors'}
</Text>
</Pressable>
</View>
<ScrollView scrollEnabled={shouldScroll}>
{list.map(item => (
<RenderListItem
key={item.path}
item={item}
onPanStateChange={value => setShouldScroll(!value)}
{...{ currentPlaybackSpeed, changeSpeed }}
/>
))}
</ScrollView>
</View>
<LivePlayerComponent setList={setList} />
</View>
</GestureHandlerRootView>
</View>
);
};
export default function App() {
return (
<SafeAreaProvider>
<AppContainer />
</SafeAreaProvider>
);
}