Comments (10)
Hey, @n-ii-ma, does this example fix the issue?
App.tsx
import React from 'react';
import { View, Button, StyleSheet } from 'react-native';
import Sound from 'react-native-sound'
Sound.setCategory('Playback');
var whoosh = new Sound('whoosh.mp3', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('failed to load the sound', error);
return;
}
});
function App(): JSX.Element {
function playSound() {
whoosh.play((success) => {
if (!success) { console.log('Playback failed due to decoding errors') }
});
}
return (
<View style={styles.container}>
<Button title='Play Sound' onPress={playSound} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent:'center',
alignItems:'center'
}
})
export default App;
Environment
package | version |
---|---|
react-native | 0.71.3 |
react-native-sound | 0.11.2 |
from react-native-sound.
Hey, @n-ii-ma, does this example fix the issue?
App.tsx
import React from 'react'; import { View, Button, StyleSheet } from 'react-native'; import Sound from 'react-native-sound' Sound.setCategory('Playback'); var whoosh = new Sound('whoosh.mp3', Sound.MAIN_BUNDLE, (error) => { if (error) { console.log('failed to load the sound', error); return; } }); function App(): JSX.Element { function playSound() { whoosh.play((success) => { if (!success) { console.log('Playback failed due to decoding errors') } }); } return ( <View style={styles.container}> <Button title='Play Sound' onPress={playSound} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent:'center', alignItems:'center' } }) export default App;
Environment
package version
react-native 0.71.3
react-native-sound 0.11.2
On iOS it does work in this way but on Android I have to call the .play()
method inside the callback of creating the Sound
instance for it to work and that results in it playing as soon as it's created.
from react-native-sound.
Hmm that is weird, it works on my Android device. What can you see in the Android Studio logcat when pressing the button to play the sound? (without having the .play()
inside the callback)
I get those 2 lines everytime the audio is played:
from react-native-sound.
At first it logs the same lines as you but then logs these:
Might be because I'm calling the .play
method inside a useEffect
since by doing a button press it does actually play.
from react-native-sound.
I just tried calling the .play()
method with a button and still nothing. It seems that the asset won't get played at first but then it will.
Getting a lot of headaches with this library, TBH.
from react-native-sound.
You can solve it using the useState()
hook, this way, you can display a loading screen until the asset has been loaded properly & then dismiss it. Also, wrap the function with useMemo()
so that it will only be executed on the first render, like this:
const [loading, setLoading] = useState(true)
const whoosh = useMemo(() => {
return (
new Sound('whoosh.mp3', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('failed to load the sound', error);
return;
}
setLoading(false)
})
)
},[]);
from react-native-sound.
I did as you mentioned and still nothing but I just realized that I'm releasing the audio in the cleanup function of useEffect
and that seems to have been the issue here since the cleanup function runs when the conditions set in useEffect
are not met and this causes the audio not to play. This is how my useEffect
looks at the moment:
const [loading, setLoading] = useState(true); // Sound loading state
const orderMusicAudio = useMemo(() => {
return new Sound('order_music.mp3', Sound.MAIN_BUNDLE, error => {
// Return if there's an error
if (error) {
return;
}
// Set indefinite loop
orderMusicAudio.setNumberOfLoops(-1);
// Set loading to false
setLoading(false);
});
}, []);
// Play sound if an order has been selected
useEffect(() => {
// Play sound if sound has loaded, the courier has incoming orders and hasn't yet accepted any
if (!loading && hasOrders && isObjEmpty(acceptedOrder)) {
// Start vibration
Vibration.vibrate([1000, 1000], true);
// Play the audio file
// After it's completed, stop the vibration and release the audio player resource
orderMusicAudio.play(() => {
Vibration.cancel();
orderMusicAudio.release();
});
}
// Stop playing the audio file if otherwise
else {
// After the audio is stopped, stop the vibration and release the audio player resource
orderMusicAudio.stop(() => {
Vibration.cancel();
orderMusicAudio.release();
});
}
// Release the audio player resource on unmount
return () => {
console.log('RELEASE');
orderMusicAudio.release();
};
}, [loading, hasOrders, acceptedOrder]);
This is for an app like Uber for the drivers which will play a sound after an order arrives via a Socket Connection.
(The reason I'm releasing the audio after each successful play and stop is for performance purposes although to be honest, I'm beginning to doubt its usefulness)
I myself am a bit confused here for even if the cleanup function gets called, after the conditions are met, the .play()
method is invoked and the sound should play again but it doesn't.
Also, as I mentioned before, this problem only occurs on Android.
from react-native-sound.
You might be over-complicating things with .release()
, try this instead:
useEffect(() => {
if(loading) return
if (hasOrders && isObjEmpty(acceptedOrder)) {
Vibration.vibrate([1000, 1000], true);
orderMusicAudio.play((success) => {
if (!success) { console.log('Playback failed due to decoding errors') }
});
} else {
orderMusicAudio.stop()
}
},[loading, hasOrders, acceptedOrder])
Let me know if it works now!
from react-native-sound.
Yeah this does work indeed but since no cleanup is done in the useEffect
, closing the app while the audio is still playing doesn't release the resource and stop the audio.
One workaround I found was to just stop playing the sound inside the cleanup function yet I'm wondering if not releasing the audio might lead to memory leak issues.
from react-native-sound.
This will help https://www.youtube.com/watch?v=vVI7ZAZq5e0
from react-native-sound.
Related Issues (20)
- setCategory() mixWithOthers boolean does not work HOT 3
- using new AvAudioPlayer feature fadeDuration issue. setVolume(1, {fadeDuration:3}) doesnt work it just plays at volume 1 immediately HOT 1
- Is there any audio puase/stop listener? HOT 2
- Fail to load sound in Android apk. { extra: -2147483648, what: 1 } HOT 1
- Update import format to XCode 14.2 compat
- Audio after playing not stopped
- Sound.setCategory('Playback') not working
- Play function stops working after playing multiple videos HOT 1
- Playing the next track in the done callback of the play() function doesn't work HOT 1
- Can not build in Windows HOT 4
- It is not working on Ios version 16.6 HOT 1
- Uncaught Error: Cannot read property 'IsAndroid' of null HOT 2
- React Native 0.71.0 incompatibility HOT 1
- Include Guidelines for Allowing Assets in Audio Files
- Can't play sound from "App Group" paths.
- onEnd callback is not fired on Android if setSpeed() HOT 3
- × Build failed with message C:\Users\91626\Downloads\testwindowsapp\node_modules\react-native-sound\windows\RNSoundModule\RNSoundModule\RNSoundPackage.cs(1,7): error CS0246: The type or namespace name 'ReactNative' could not be found (are you missing a using directive or an assembly reference?) [C:\Users\91626\Downloads\testwindowsapp\node_modules\react-native-sound\windows\RNSoundModule\RNSoundModule\RNSoundModule.csproj]. Check your build configuration. HOT 3
- delay between sounds played HOT 1
- Is there a software update plan? HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react-native-sound.