I am a somewhat beginner coder using Expo-Av.For this particular project, I would like the audio to start immediately after the page loads as well as loop if possible. My code is as follows:
const Music = require('./assets/sounds/MellowMusic.mp3');
export default function App() {
const [Loaded, setLoaded] = useState(false);
const [Loading, setLoading] = useState(false);
const sound = useRef( new Audio.Sound());
React.useEffect(() => {
LoadAudio();
}, []);
const PlayAudio = async () => {
try {
const result = await sound.current.getStatusAsync({
});
if (result.isLoaded) {
if (result.isPlaying === false) {
sound.current.playAsync();
}
}
} catch (error) {}
};
const PauseAudio = async () => {
try {
const result = await sound.current.getStatusAsync ();
if (result.isLoaded) {
if (result.isPlaying === true) {
sound.current.pauseAsync();
}
}
} catch (error) {}
}
const LoadAudio = async () => {
setLoading(true);
const checkLoading = await sound.current.getStatusAsync ();
if (checkLoading.isLoaded === false) {
try {
const result = await sound.current.loadAsync(Music, {}, true);
if (result.isLoaded === false) {
setLoading(false);
console.log('Error In Loading Audio');
} else {
setLoading(false);
setLoaded(true);
}
} catch (error) {
console.log(error);
setLoading(false);
}
} else{
setLoading(false);
}
};
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<View style = {styles.buttons}>
<Pressable style ={styles.play} onPress={PlayAudio}>
<Image source = {require('./assets/images/PlayButton.png')}></Image>
</Pressable>
<Pressable style = {styles.pause} onPress={PauseAudio}>
<Image source = {require('./assets/images/PauseButton.png')}></Image>
</Pressable>
<StatusBar style="auto" />
</View>
</View>
);
}
I have tried adding “shouldPlay” “shouldPlay:true”, “shouldLoop” and “shouldLoop:true” to the playAudio const to no avail.