3
import AlphService from './AlphService';

export default class MyClass extends React.Component {
 alphService;
 constructor(props) {
  super(props);
  alphService = new AlphService();
  this.state = alphService.getState();
 }
 componentWillMount() {
    this.play(this.state.sound);
  }

  play(source) {
   console.log(source);
   Audio.setIsEnabledAsync(true);
   const sound = new Audio.Sound();
   const play_sound = (async () => {
    await sound.loadAsync(require(source)); //Error Here
    await sound.playAsync();
   })();
  }
}

AlphService.js

export default class alphService {
 stateObj = {
  sound: ""
 };
 getState(){
  this.stateObj.sound = "../assets/sounds/c.mp3"; 
  return this.stateObj;
 }
}

ERROR: components/Alphabet.js:Invalid call at line 51: require(source)

and also try I return require(soundPathVar) object from getState() method and remove required from play(), then same error.

I am beginner in react-native and I want to try creating a dynamic sound file path. So can you please help me if I am doing wrong. Thank in advance.

1 Answer 1

6

I faced this when i was trying to require dynamic images, it turned out that require only accepts specific source even require("SOURCE/" + "something.png") doesn't work, it should be require("SOURCE/something.png"). Try this:

export default class alphService {
 stateObj = {
  sound: ""
 };
 getState(){
  this.stateObj.sound = require("../assets/sounds/c.mp3"); 
  return this.stateObj;
 }
}

You can create a json file containing all paths and use it like so:

export default const paths = {
    file1: require("path/to/file1.png"),
    file2: require("path/to/file2.png")
}

then in your component import this paths file and use it like so (for example an image):

<Image source={paths.file1}/>
2
  • yes its work, because is static path to require. dynamic path is not possible? Commented Dec 26, 2018 at 9:03
  • Dynamic path is unfortunately not possible yeah, if you want you can create a json file containing all paths then you can use import this file and use it, I'll update my answer with an example Commented Dec 28, 2018 at 3:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.