我目前正在构建一个应用程序,我希望在其中有一个播放按钮,按下该按钮可以播放音频文件。我这样做的方法是创建一个声音播放器组件来创建按钮和音频同步,这样我就可以在我使用它的主屏幕中调用该组件。当我手动放置时,我可以让声音播放器组件正常工作mp3 文件路径在它的正确位置,但当我尝试将它作为参数传递时却没有。看看我下面的代码,看看你是否能帮助解决这个问题。
声音播放器组件
import * as React from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { Audio } from 'expo-av';
function SoundPlayer({ mp3 }) {
const [sound, setSound] = React.useState();
async function playSound() {
console.log('Loading Sound');
const { sound } = Audio.Sound.createAsync({ mp3 });
setSound(sound);
console.log('Playing Sound');
await sound.playAsync(); }
React.useEffect(() => {
return sound
? () => {
console.log('Unloading Sound');
sound.unloadAsync(); }
: undefined;
}, [sound]);
return (
<View style = {styles.container}>
<Button title="Play Sound" onPress={playSound} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}
})
export default SoundPlayer
应用程序屏幕
export default function App() {
return (
<SoundPlayer mp3 = {require('/Users/viswajithkumar/DharmaWorldwide/Screens/assets/Audio/FrenchTouch.mp3')}/>
);
}