Context: I'm trying to make a timer app with React Native, Expo, and Expo-AV.
I'm initialising a stock app with Managed workflow and trying to play an mp3 file using expo-av (9.2.3)
. I saw another issue where no sound was playing on Moto G5, Android 8. For me, sound doesn't play for Moto G6 Android 9, iPhone SE iOS 14.6, OR on the web. App.json
and package.json
attached.
managed
Android, Web
42.0.3
Expo CLI 4.9.0 environment info:
expo init my-app
expo install expo-av
app.js
import { StatusBar } from 'expo-status-bar';
import React, { useEffect } from 'react';
import { Audio } from 'expo-av';
import { StyleSheet, Text, View } from 'react-native';
export default function App() {
useEffect(() => {
playSound()
}, []);
async function playSound() {
const sound = new Audio.Sound();
try {
await sound.loadAsync(require('./sound.mp3'));
await sound.playAsync();
await sound.unloadAsync();
} catch (error) {
console.error(error)
}
}
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
expo start
w
with terminal.I received a suggestion on how to change the functions I use to play the audio in the Expo Github Issues.
Before, my code was:
async function playSound() {
const sound = new Audio.Sound();
try {
await sound.loadAsync(require('./sound.mp3'));
await sound.playAsync();
await sound.unloadAsync();
} catch (error) {
console.error(error)
}
}
Now, I used the .setPositionAsync()
and .playAsync()
functions, as well as the { shouldPlay: true}
flag. This code worked after I updated to "expo": "^45.0.8"
and "expo-av": "~11.2.3"
as well (since Expo 42 is deprecated). I haven't tested this on versions of Expo besides 42 and 45.
async function playSound() {
const sound = new Audio.Sound();
try {
await sound.loadAsync(require('./sound.mp3'), {shouldPlay: true});
await sound.setPositionAsync(0);
await sound.playAsync();
} catch (error) {
console.error(error)
}
}