react-nativereact-native-sound

react-native-sound in componentDidMount


I want to play music in componentDidMount but my code doesn't works

import React,{Component} from 'react'
import Nav from './Nav'
import Sound from 'react-native-sound'
const play = new Sound('music.mp3')

class App extends Component {
  componentDidMount(){
          play.play()
  }
  render(){ 
    return(
      <Nav />
    )
  }}
export default App

Solution

  • According to the docs you should use the callback in the constructor:

    import React,{Component} from 'react'
    import Nav from './Nav'
    import Sound from 'react-native-sound'
    
    class App extends Component {
      componentDidMount(){
        const play = new Sound('music.mp3', (error, play) => {
          if (error) return
          else play.play(() => {
            play.release() // release when done to release resources
          })
        })
      }
      render(){ 
        return(
          <Nav />
        )
      }}
    export default App