我正在建立一个小的声音播放器页面。我正在使用expo-av库。当用户向前{NavigationEvents onWillBlur}工作时,以及向后的用户未执行时,我得到通知。
我需要达到的是:1)当用户向后或向前离开页面时,停止播放声音。2)如果用户按下播放两次,则声音将被播放两次,所以我不希望它已经运行时再次播放
如果可以使用其他任何库代替expo-av?
import React, {useState} from 'react';
import {View, Text, Button, StyleSheet, TouchableOpacity } from 'react-native';
import { NavigationEvents } from 'react-navigation';
import { Audio } from 'expo-av';
import {AntDesign, Entypo} from '@expo/vector-icons';
const PlaySound = ({link}) => {
const [error, setError] = useState('')
const soundObject = new Audio.Sound();
const mySound = async () => {
try {
await soundObject.loadAsync({ uri : link });
await soundObject.playAsync();
} catch (err) {
setError('Wait while uploading your sound');
}
}
const stopSound = async () => {
try {
await soundObject.stopAsync(mySound);
} catch (error) {
setError('You must Play Sound First')
}
}
const pause = async () => {
try {
await soundObject.pauseAsync(mySound);
} catch (error) {
setError('Something went wrong !!! Please try again');
}
}
return (
<View>
<NavigationEvents onWillBlur = {stopSound} />
<Text>Play Sound</Text>
<View style = {styles.row}>
<TouchableOpacity
onPress = {mySound}>
<AntDesign name = 'caretright' size = {25} />
</TouchableOpacity>
<TouchableOpacity
onPress = {stopSound} >
<Entypo name = 'controller-stop' size = {25}/>
</TouchableOpacity>
<TouchableOpacity
onPress = {pause}>
<AntDesign name = 'pause' size = {25} />
</TouchableOpacity>
</View>
{error ? <Text>{error} </Text> : null }
</View>
);
};
const styles = StyleSheet.create({
row : {
flexDirection : 'row',
justifyContent : 'space-between',
marginVertical : 10
}
});
export default PlaySound;
对于问题1,您必须在退出页面时停止播放器。您可以使用useEffect挂钩。会是这样,
useEffect(() => {
return () => {
stopSound();
}
}, []);
因此,在上面的useEffect挂钩中,当组件从屏幕上卸下时(向前或向后),返回的函数将运行。
对于第二个问题,您必须禁用播放按钮,以避免多次单击。您可以使用useState
钩子创建状态,并在单击“播放”按钮时将其设为false
,然后传递此playButtonState以禁用“播放按钮可触摸不透明度”的属性。
我希望您现在明白了。