Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play sound in React Native?

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?

like image 364
Tri Avatar asked Dec 12 '18 06:12

Tri


People also ask

How do you play sound in react-native Expo?

try { const { sound: soundObject, status } = await Audio. Sound. createAsync( require('./assets/sounds/hello. mp3'), { shouldPlay: true } ); // Your sound is playing! }


1 Answers

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.

like image 174
Mohammed Ashfaq Avatar answered Oct 16 '22 17:10

Mohammed Ashfaq