Migrate to react-native-track-player and play audio even in the background

This commit is contained in:
Danish Ahmed Mirza 2022-06-13 23:10:36 +05:30 committed by Danish
parent 811c91906f
commit 7855cfbf66
8 changed files with 311 additions and 330 deletions

View File

@ -4,7 +4,7 @@ import { Text } from 'react-native';
import { IMessageAttachments } from './interfaces';
import Image from './Image';
import Audio from './Audio';
import Audio from './Components/Audio';
import Video from './Video';
import Reply from './Reply';
import Button from '../Button';

View File

@ -1,321 +0,0 @@
import React from 'react';
import { StyleProp, StyleSheet, Text, TextStyle, View } from 'react-native';
import { Audio, AVPlaybackStatus, InterruptionModeAndroid, InterruptionModeIOS } from 'expo-av';
import moment from 'moment';
import { dequal } from 'dequal';
import { activateKeepAwake, deactivateKeepAwake } from 'expo-keep-awake';
import { Sound } from 'expo-av/build/Audio/Sound';
import Touchable from './Touchable';
import Markdown from '../markdown';
import { CustomIcon } from '../CustomIcon';
import sharedStyles from '../../views/Styles';
import { themes } from '../../lib/constants';
import {
isAndroid
// isIOS
} from '../../lib/methods/helpers';
import MessageContext from './Context';
import ActivityIndicator from '../ActivityIndicator';
import { withDimensions } from '../../dimensions';
import { TGetCustomEmoji } from '../../definitions/IEmoji';
import { IAttachment } from '../../definitions';
import { TSupportedThemes } from '../../theme';
import Slider from './Slider';
import { downloadAudioFile } from '../../lib/methods/audioFile';
interface IButton {
loading: boolean;
paused: boolean;
theme: TSupportedThemes;
disabled?: boolean;
onPress: () => void;
}
interface IMessageAudioProps {
file: IAttachment;
isReply?: boolean;
style?: StyleProp<TextStyle>[];
theme: TSupportedThemes;
getCustomEmoji: TGetCustomEmoji;
scale?: number;
}
interface IMessageAudioState {
loading: boolean;
currentTime: number;
duration: number;
paused: boolean;
}
const mode = {
allowsRecordingIOS: false,
playsInSilentModeIOS: true,
staysActiveInBackground: true,
shouldDuckAndroid: true,
playThroughEarpieceAndroid: false,
interruptionModeIOS: InterruptionModeIOS.DoNotMix,
interruptionModeAndroid: InterruptionModeAndroid.DoNotMix
};
const styles = StyleSheet.create({
audioContainer: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
height: 56,
borderWidth: 1,
borderRadius: 4,
marginBottom: 6
},
playPauseButton: {
marginHorizontal: 10,
alignItems: 'center',
backgroundColor: 'transparent'
},
audioLoading: {
marginHorizontal: 8
},
duration: {
marginHorizontal: 12,
fontSize: 14,
...sharedStyles.textRegular
}
});
const formatTime = (seconds: number) => moment.utc(seconds * 1000).format('mm:ss');
const BUTTON_HIT_SLOP = { top: 12, right: 12, bottom: 12, left: 12 };
const Button = React.memo(({ loading, paused, onPress, disabled, theme }: IButton) => (
<Touchable
style={styles.playPauseButton}
disabled={disabled}
onPress={onPress}
hitSlop={BUTTON_HIT_SLOP}
background={Touchable.SelectableBackgroundBorderless()}
>
{loading ? (
<ActivityIndicator style={[styles.playPauseButton, styles.audioLoading]} />
) : (
<CustomIcon
name={paused ? 'play-filled' : 'pause-filled'}
size={36}
color={disabled ? themes[theme].tintDisabled : themes[theme].tintColor}
/>
)}
</Touchable>
));
Button.displayName = 'MessageAudioButton';
class MessageAudio extends React.Component<IMessageAudioProps, IMessageAudioState> {
static contextType = MessageContext;
private sound: Sound;
constructor(props: IMessageAudioProps) {
super(props);
this.state = {
loading: false,
currentTime: 0,
duration: 0,
paused: true
};
this.sound = new Audio.Sound();
this.sound.setOnPlaybackStatusUpdate(this.onPlaybackStatusUpdate);
}
async componentDidMount() {
const { file } = this.props;
const { baseUrl, user } = this.context;
let url = file.audio_url;
if (url && !url.startsWith('http')) {
url = `${baseUrl}${file.audio_url}`;
}
this.setState({ loading: true });
try {
if (url) {
const audio = await downloadAudioFile(`${url}?rc_uid=${user.id}&rc_token=${user.token}`, url);
await this.sound.loadAsync({ uri: audio });
}
} catch {
// Do nothing
}
this.setState({ loading: false });
}
shouldComponentUpdate(nextProps: IMessageAudioProps, nextState: IMessageAudioState) {
const { currentTime, duration, paused, loading } = this.state;
const { file, theme } = this.props;
if (nextProps.theme !== theme) {
return true;
}
if (nextState.currentTime !== currentTime) {
return true;
}
if (nextState.duration !== duration) {
return true;
}
if (nextState.paused !== paused) {
return true;
}
if (!dequal(nextProps.file, file)) {
return true;
}
if (nextState.loading !== loading) {
return true;
}
return false;
}
componentDidUpdate() {
const { paused } = this.state;
if (paused) {
deactivateKeepAwake();
} else {
activateKeepAwake();
}
}
async componentWillUnmount() {
try {
await this.sound.stopAsync();
} catch {
// Do nothing
}
}
onPlaybackStatusUpdate = (status: AVPlaybackStatus) => {
if (status) {
this.onLoad(status);
this.onProgress(status);
this.onEnd(status);
}
};
onLoad = (data: AVPlaybackStatus) => {
if (data.isLoaded && data.durationMillis) {
const duration = data.durationMillis / 1000;
this.setState({ duration: duration > 0 ? duration : 0 });
}
};
onProgress = (data: AVPlaybackStatus) => {
if (data.isLoaded) {
const { duration } = this.state;
const currentTime = data.positionMillis / 1000;
if (currentTime <= duration) {
this.setState({ currentTime });
}
}
};
onEnd = async (data: AVPlaybackStatus) => {
if (data.isLoaded) {
if (data.didJustFinish) {
try {
await this.sound.stopAsync();
this.setState({ paused: true, currentTime: 0 });
} catch {
// do nothing
}
}
}
};
get duration() {
const { currentTime, duration } = this.state;
return formatTime(currentTime || duration);
}
togglePlayPause = () => {
const { paused } = this.state;
this.setState({ paused: !paused }, this.playPause);
};
playPause = async () => {
const { paused } = this.state;
try {
if (paused) {
await this.sound.pauseAsync();
} else {
await Audio.setAudioModeAsync(mode);
await this.sound.playAsync();
}
} catch {
// Do nothing
}
};
onValueChange = async (value: number) => {
try {
this.setState({ currentTime: value });
await this.sound.setPositionAsync(value * 1000);
} catch {
// Do nothing
}
};
render() {
const { loading, paused, currentTime, duration } = this.state;
const {
file,
getCustomEmoji,
theme,
// scale,
isReply,
style
} = this.props;
const { description } = file;
const { baseUrl, user } = this.context;
if (!baseUrl) {
return null;
}
let thumbColor;
if (isAndroid && isReply) {
thumbColor = themes[theme].tintDisabled;
} else if (isAndroid) {
thumbColor = themes[theme].tintColor;
}
return (
<>
<Markdown
msg={description}
style={[isReply && style]}
baseUrl={baseUrl}
username={user.username}
getCustomEmoji={getCustomEmoji}
theme={theme}
/>
<View
style={[
styles.audioContainer,
{ backgroundColor: themes[theme].chatComponentBackground, borderColor: themes[theme].borderColor }
]}
>
<Button disabled={isReply} loading={loading} paused={paused} onPress={this.togglePlayPause} theme={theme} />
<Slider
value={currentTime}
maximumValue={duration}
onValueChange={this.onValueChange}
thumbTintColor={thumbColor}
minimumTrackTintColor={themes[theme].tintColor}
disabled={isReply}
maximumTrackTintColor={themes[theme].auxiliaryText}
// thumbImage={isIOS ? { uri: 'audio_thumb', scale } : undefined}
/>
<Text style={[styles.duration, { color: themes[theme].auxiliaryText }]}>{this.duration}</Text>
</View>
</>
);
}
}
export default withDimensions(MessageAudio);

View File

@ -4,8 +4,8 @@ import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import Touchable from 'react-native-platform-touchable';
import Animated, { useSharedValue, useAnimatedStyle, interpolate } from 'react-native-reanimated';
import styles, { SLIDER_THUMB_RADIUS } from './styles';
import { useTheme } from '../../theme';
import styles, { SLIDER_THUMB_RADIUS } from '../../styles';
import { useTheme } from '../../../../theme';
interface ISliderProps {
value: number;

View File

@ -0,0 +1,232 @@
import React, { useContext, useEffect, useState } from 'react';
import { StyleProp, StyleSheet, Text, TextStyle, View } from 'react-native';
import moment from 'moment';
import { activateKeepAwake, deactivateKeepAwake } from 'expo-keep-awake';
import Slider from '@react-native-community/slider';
import TrackPlayer, { Event, useTrackPlayerEvents, State, useProgress } from 'react-native-track-player';
import Touchable from '../../Touchable';
import Markdown from '../../../markdown';
import { CustomIcon } from '../../../CustomIcon';
import sharedStyles from '../../../../views/Styles';
import { themes } from '../../../../lib/constants';
import {
isAndroid,
isIOS
// isIOS
} from '../../../../lib/methods/helpers';
import MessageContext from '../../Context';
import ActivityIndicator from '../../../ActivityIndicator';
import { TGetCustomEmoji } from '../../../../definitions/IEmoji';
import { IAttachment } from '../../../../definitions';
import { TSupportedThemes } from '../../../../theme';
import { setupService } from './services';
// import Slider from './Slider';
interface IButton {
loading: boolean;
paused: boolean;
theme: TSupportedThemes;
disabled?: boolean;
onPress: () => void;
}
interface IMessageAudioProps {
file: IAttachment;
isReply?: boolean;
style?: StyleProp<TextStyle>[];
theme: TSupportedThemes;
getCustomEmoji: TGetCustomEmoji;
scale?: number;
}
const styles = StyleSheet.create({
audioContainer: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
height: 56,
borderWidth: 1,
borderRadius: 4,
marginBottom: 6
},
playPauseButton: {
marginHorizontal: 10,
alignItems: 'center',
backgroundColor: 'transparent'
},
audioLoading: {
marginHorizontal: 8
},
duration: {
marginHorizontal: 12,
fontSize: 14,
...sharedStyles.textRegular
},
slider: {
flex: 1
}
});
const formatTime = (seconds: number) => moment.utc(seconds * 1000).format('mm:ss');
const BUTTON_HIT_SLOP = { top: 12, right: 12, bottom: 12, left: 12 };
const Button = React.memo(({ loading, paused, onPress, disabled, theme }: IButton) => (
<Touchable
style={styles.playPauseButton}
disabled={disabled}
onPress={onPress}
hitSlop={BUTTON_HIT_SLOP}
background={Touchable.SelectableBackgroundBorderless()}>
{loading ? (
<ActivityIndicator style={[styles.playPauseButton, styles.audioLoading]} />
) : (
<CustomIcon
name={paused ? 'play-filled' : 'pause-filled'}
size={36}
color={disabled ? themes[theme].tintDisabled : themes[theme].tintColor}
/>
)}
</Touchable>
));
Button.displayName = 'MessageAudioButton';
const MessageAudio = ({ file, isReply, style, theme, getCustomEmoji, scale }: IMessageAudioProps) => {
const [loading, setLoading] = useState(false);
const [paused, setPaused] = useState(true);
const { baseUrl, user } = useContext(MessageContext);
const { position, duration } = useProgress();
useEffect(() => {
const setup = async () => {
setupService();
let url = file.audio_url;
if (url && !url.startsWith('http')) {
url = `${baseUrl}${file.audio_url}`;
}
setLoading(true);
try {
await TrackPlayer.add([{ url: `${url}?rc_uid=${user.id}&rc_token=${user.token}` }]);
} catch {
// Do nothing
}
setLoading(false);
};
setup();
return () => {
TrackPlayer.stop();
};
}, []);
useEffect(() => {
playPause();
}, [paused]);
useEffect(() => {
if (paused) {
deactivateKeepAwake();
} else {
activateKeepAwake();
}
}, [paused, position, duration, file, loading, theme]);
useTrackPlayerEvents([Event.PlaybackState], ({ state }) => {
if (state === State.Stopped) {
try {
TrackPlayer.stop();
setPaused(true);
} catch {
// do nothing
}
}
});
const getDuration = () => formatTime(position || duration);
const togglePlayPause = () => {
setPaused(!paused);
};
const playPause = () => {
try {
if (paused) {
TrackPlayer.pause();
} else {
TrackPlayer.play();
}
} catch {
// Do nothing
}
};
const onValueChange = async (value: number) => {
try {
await TrackPlayer.seekTo(value);
} catch {
// Do nothing
}
};
const { description } = file;
if (!baseUrl) {
return null;
}
let thumbColor;
if (isAndroid && isReply) {
thumbColor = themes[theme].tintDisabled;
} else if (isAndroid) {
thumbColor = themes[theme].tintColor;
}
return (
<>
<Markdown
msg={description}
style={[isReply && style]}
baseUrl={baseUrl}
username={user.username}
getCustomEmoji={getCustomEmoji}
theme={theme}
/>
<View
style={[
styles.audioContainer,
{ backgroundColor: themes[theme].chatComponentBackground, borderColor: themes[theme].borderColor }
]}>
<Button disabled={isReply} loading={loading} paused={paused} onPress={togglePlayPause} theme={theme} />
{/* <Slider
value={currentTime}
maximumValue={duration}
onValueChange={this.onValueChange}
thumbTintColor={thumbColor}
minimumTrackTintColor={themes[theme].tintColor}
disabled={isReply}
maximumTrackTintColor={themes[theme].auxiliaryText}
// thumbImage={isIOS ? { uri: 'audio_thumb', scale } : undefined}
/> */}
<Slider
disabled={isReply}
style={styles.slider}
value={position}
maximumValue={duration}
minimumValue={0}
thumbTintColor={thumbColor}
minimumTrackTintColor={themes[theme].tintColor}
maximumTrackTintColor={themes[theme].auxiliaryText}
onValueChange={onValueChange}
thumbImage={isIOS ? { uri: 'audio_thumb', scale } : undefined}
/>
<Text style={[styles.duration, { color: themes[theme].auxiliaryText }]}>{getDuration()}</Text>
</View>
</>
);
};
export default MessageAudio;

View File

@ -0,0 +1,72 @@
import TrackPlayer, { Event, State, Capability } from 'react-native-track-player';
// import type { ProgressUpdateEvent } from 'react-native-track-player';
let wasPausedByDuck = false;
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
// eslint-disable-next-line require-await
export const playbackService = async () => {
TrackPlayer.addEventListener(Event.RemotePause, () => {
TrackPlayer.pause();
});
TrackPlayer.addEventListener(Event.RemotePlay, () => {
TrackPlayer.play();
});
TrackPlayer.addEventListener(Event.RemoteDuck, async e => {
if (e.permanent === true) {
TrackPlayer.stop();
} else if (e.paused === true) {
const playerState = await TrackPlayer.getState();
wasPausedByDuck = playerState !== State.Paused;
TrackPlayer.pause();
} else if (wasPausedByDuck === true) {
TrackPlayer.play();
wasPausedByDuck = false;
}
});
// TrackPlayer.addEventListener(Event.PlaybackQueueEnded, data => {
// console.log('Event.PlaybackQueueEnded', data);
// });
// TrackPlayer.addEventListener(Event.PlaybackTrackChanged, data => {
// console.log('Event.PlaybackTrackChanged', data);
// });
// TrackPlayer.addEventListener(Event.PlaybackProgressUpdated, (data: ProgressUpdateEvent) => {
// console.log('Event.PlaybackProgressUpdated', data);
// });
// TrackPlayer.addEventListener(Event.RemoteNext, () => {
// TrackPlayer.skipToNext();
// });
// TrackPlayer.addEventListener(Event.RemotePrevious, () => {
// TrackPlayer.skipToPrevious();
// });
};
export const setupService = async () => {
try {
await TrackPlayer.setupPlayer();
await TrackPlayer.updateOptions({
stopWithApp: false,
capabilities: [
Capability.Play,
Capability.Pause,
Capability.Stop
// Capability.SkipToNext,
// Capability.SkipToPrevious
],
compactCapabilities: [
Capability.Play,
Capability.Pause
// Capability.SkipToNext
]
});
} catch {
// Do nothing
}
};

View File

@ -1,8 +1,10 @@
import 'react-native-gesture-handler';
import 'react-native-console-time-polyfill';
import { AppRegistry } from 'react-native';
import TrackPlayer from 'react-native-track-player';
import { name as appName, share as shareName } from './app.json';
import { playbackService } from './app/containers/message/Components/Audio/services';
if (__DEV__) {
require('./app/ReactotronConfig');
@ -21,6 +23,8 @@ if (__DEV__) {
AppRegistry.registerComponent(appName, () => require('./app/index').default);
AppRegistry.registerComponent(shareName, () => require('./app/share').default);
TrackPlayer.registerPlaybackService(() => playbackService);
// For storybook, comment everything above and uncomment below
// import 'react-native-gesture-handler';
// import 'react-native-console-time-polyfill';

View File

@ -42,7 +42,6 @@
"@react-native-community/masked-view": "0.1.11",
"@react-native-community/netinfo": "6.0.0",
"@react-native-community/picker": "^1.8.1",
"@react-native-community/slider": "4.2.2",
"@react-native-cookies/cookies": "6.2.1",
"@react-native-firebase/analytics": "^14.11.0",
"@react-native-firebase/app": "^14.11.0",

View File

@ -4988,11 +4988,6 @@
resolved "https://registry.yarnpkg.com/@react-native-community/picker/-/picker-1.8.1.tgz#94f14f0aad98fa7592967b941be97deec95c3805"
integrity sha512-Sj9DzX1CSnmYiuEQ5fQhExoo4XjSKoZkqLPAAybycq6RHtCuWppf+eJXRMCOJki25BlKSSt+qVqg0fIe//ujNQ==
"@react-native-community/slider@4.2.2":
version "4.2.2"
resolved "https://registry.yarnpkg.com/@react-native-community/slider/-/slider-4.2.2.tgz#06a0de89c26c6bd03d95798b777db1872b60c066"
integrity sha512-C1ldx1ypQo+uDWx78TUBG0evLVopKYHK2mQencl+vxi4ebMTL+ipJv5MF5mEvmZWLUOAMm5AsoQNHChYUdyWrQ==
"@react-native-community/viewpager@3.3.0":
version "3.3.0"
resolved "https://registry.yarnpkg.com/@react-native-community/viewpager/-/viewpager-3.3.0.tgz#e613747a43a31a6f3278f817ba96fdaaa7941f23"