Ashish Mehta
Ashish Mehta

Reputation: 7424

Assets Audio file can not play in Expo

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.

Upvotes: 3

Views: 1857

Answers (1)

mahmoudafer
mahmoudafer

Reputation: 1181

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}/>

Upvotes: 6

Related Questions