Playing state dependent audio files in React

27 views Asked by At

I am trying to create a new state-dependent Audio instance in React. When using require(), I receive the warning, "Critical dependency: the request of a dependency is an expression." I cannot simply import the file since the audio's source is state-dependent. How can I work around this?

The following code gives the error:

playSong = () => {
    this.setState(this.state, function(){
    let source = require(this.state.songList[this.state.songIndex].src);
    let audio = new Audio(source);
    audio.play();
    });
}

The require() function only seems to work if given a literal.

1

There are 1 answers

0
Tholle On

You cannot require dynamic values, sadly.

You could import all your files into the songList array statically first, and pick the correct one from that:

const songList = [
  require('./path/to/song1.mp3'),
  require('./path/to/song2.mp3')
];

class MyComponent extends React.Component {
  playSong = () => {
    let source = songList[this.state.songIndex].src;
    let audio = new Audio(source);
    audio.play();
  };

  render () {
    // ...
  }
}