React Native how to play a sound after an "onPress"?

8.7k Views Asked by At

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.

3

There are 3 best solutions below

0
On
  1. npm install react-native-sound and link with your project.
Import sound from react-native-sound
// or
import Sound from 'react-native-sound';
  1. Put your mp3 file inside the folder and mention the path:
const requireAudio = require('./xyz.mp3');
  1. Place this code inside your "onPress" function.
    const s = new Sound(requireAudio, (e) => {
            if (e) {
              console.log('Error in SOUND', e);
              return;
            }
            s.play(() => s.release());
          });
0
On

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();
}
3
On

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()