Reputation: 69
Here is some of my code:
<TouchableOpacity
style={styles.button}
onPress={this.onPress}
>
<Text> Play Sound </Text>
</TouchableOpacity>
I want to write a function "onPress" which will play an .mp3 sound. I have already imported react-native-sound and have my .mp3 file ready to go, I just don't know how to play the sound once the onPress function is called.
Upvotes: 2
Views: 8830
Reputation: 481
npm install react-native-sound
and link with your project.Import sound from react-native-sound
// or
import Sound from 'react-native-sound';
const requireAudio = require('./xyz.mp3');
const s = new Sound(requireAudio, (e) => {
if (e) {
console.log('Error in SOUND', e);
return;
}
s.play(() => s.release());
});
Upvotes: 0
Reputation: 665
The easiest way is First to create a new instance like Following. create this in a constructor to load it when the component mount Note: please put your mp3 or wav file in android/app/src/main/res/raw
const whoosh = new Sound('swoosh.mp3', Sound.MAIN_BUNDLE);
just call it in your function
whoosh.play()
Upvotes: 0
Reputation: 169
In my opinion, if you want to listen the sound, you can try this. Syntax = react.
Import Sound from "react-native-sound";
Sound.setCategory('Playback');
const whoosh = new Sound('whoosh.mp3', Sound.MAIN_BUNDLE, (error) => {
if (error) {
console.log('failed to load the sound', error);
return;
};
whoosh.play((success) => {
if (success) {
console.log('successfully finished playing');
} else {
console.log('playback failed due to audio decoding errors');
reset the player to its uninitialized state (android only)
whoosh.reset();
}
Upvotes: 1