16

I want to play a sound in React Native.

I have try to read here in zmxv/react-native-sound, but as a beginner like me, that's documentation make me confused how to apply that in React Native code.

Before I have try this one to make react native play sound on event and make a code like this:

import React, { Component } from 'react'
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'
const Sound = require('react-native-sound')


export default class MovieList extends Component {

    handlePress() {
        // Play some sound here
        let hello = new Sound('motorcycle.mp3', Sound.MAIN_BUNDLE, (error) => {
            if (error) {
              console.log(error)
            }
          })

          hello.play((success) => {
            if (!success) {
              console.log('Sound did not play')
            }
          })
    }

    render() {
        const { movie } = this.props
        return (
            <TouchableOpacity onPress={this.handlePress.bind(this)}>
                <View>
                      <Text>Start</Text>
                </View>
            </TouchableOpacity>
        )
    }
}

And this is where I put my audio:

MyProject/android/app/src/main/res/raw/motorcycle.mp3

Project structure

Project Structure

So, what's wrong in my code?

A J
  • 3,970
  • 14
  • 38
  • 53
Tri
  • 369
  • 1
  • 4
  • 13

5 Answers5

13

This will preload the sound and when you press the play button it will play it.

export default class MovieList extends Component {
    componentDidMount(){
      this.hello = new Sound('whoosh.mp3', Sound.MAIN_BUNDLE, (error) => {
        if (error) {
          console.log('failed to load the sound', error);
          return;
        }
      });
    }
    
    
    handlePress() {
      this.hello.play((success) => {
        if (!success) {
          console.log('Sound did not play')
        }
      })
    }

    render() {
        const { movie } = this.props
        return (
            <TouchableOpacity onPress={this.handlePress.bind(this)}>
                <View>
                      <Text>Start</Text>
                </View>
            </TouchableOpacity>
        )
    }
}

If you are looking to play sound tracks from a list of sounds please check this gist for detailed code.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Mohammed Ashfaq
  • 3,353
  • 2
  • 15
  • 22
  • Thanks @Mohammed Ashfaq, your answer work perfectly, but i have make a simple one with my code. – Tri Dec 12 '18 at 08:50
  • @mohammed how to play sound whenever view will load, also how to play multiple sounds on music list selection. – Chandni Dec 31 '20 at 08:16
  • @Chandni. Please check this link to play multiple sounds from a music list. [Link](https://gist.github.com/rickyansari/920f3bfc6c767ef1a078eb5e3f586cd0) – Mohammed Ashfaq Feb 23 '21 at 11:25
12

Thanks very much who has answer to this question, but i have resolve this with this simple one:

import React, { Component } from 'react'
import { Text, View, TouchableOpacity } from 'react-native'
import Sound from 'react-native-sound';

export default class MovieList extends Component {

    sound = new Sound('motorcycle.mp3');

    playSound = () => {
        this.sound.play()
    }

    render() {
        return (
            <View>
                <TouchableOpacity onPress={this.playSound}>
                    <View>
                        <Text>Start</Text>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }
}
Tri
  • 369
  • 1
  • 4
  • 13
5

Try this code for play sound:

setTimeout(() => {
     var sound = new Sound("motorcycle.mp3",Sound.MAIN_BUNDLE, (error) => {
                     /* ... */
     });

     setTimeout(() => {
         sound.play((success) => {
                  /* ... */
         });
    }, 100);
}, 100);

It's hacky and solved by https://github.com/zmxv/react-native-sound/issues/89#issuecomment-276678935

Vishal Jadav
  • 924
  • 9
  • 11
1

For iOS what worked for me is the following:

  1. Checked that my resource file was being played in xCode
    • Open xCode
    • Select the file
    • Click play in the xCode player
  2. Once it was playing sound (had issues with some files, possibly encoding),
    • Add the file as resource (Make sure is in Build Phases)
  3. Compile the project in xCode and run it from there
    • Note: Every time you change the resources or expect new resources you need to compile your Native application either by doing it from xCode or npm run ios

This is my code:

const sound = new Sound(
    "myFile.mp3",
    Sound.MAIN_BUNDLE,
    error => {
      if (error) {
        console.log("failed to load the sound", error);
        return;
      }
      sound.play(() => sound.release());
    }
  );
// The play dispatcher
sound.play();
0

if you are using Audio from Expo then this may help

async componentWillMount() {
    this.backgroundMusic = new Audio.Sound();
    this.buttonFX = new Audio.Sound();
    try {
        await this.backgroundMusic.loadAsync(
            require("../../assets/music/Komiku_Mushrooms.mp3")
        );
        await this.buttonFX.loadAsync(
            require("../../assets/sfx/button.wav")
        );
        // ...
    }
}

You only need one line of code to play the sound effect. On the top of the onPlayPress event handler, add the following:

onPlayPress = () => {
    this.buttonFX.replayAsync();
    // ...
}

Notice how I used replayAsync instead of playAsync – it’s because we may use this sound effect more than one time, and if you use playAsync and run it multiple times, it will only play the sound for the first time. It will come in handy later, and it’s also useful for continuing with the Game screen. See more full example

Axel Köhler
  • 911
  • 1
  • 8
  • 34
Asad Raza
  • 1
  • 2