Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative solution to require audio dynamically using expo-av

I'm developing an audio application where I download all the audio files at once and then play them using expo-av library. The issue is when I try to require the audio file, I get the following error

Invalid call at line 77: require(audioUrl)
Failed building JavaScript bundle.

I'm aware that we cannot require dynamically in react-native. I would like to know if there is any alternative solution to play downloaded audios?

The function where I require downloaded audio file

const _loadNewPlaybackInstance = async isPlaying => {
    if (playBackInstance != null) {
      await playBackInstance.unloadAsync()
      await setPlaybackInstance(null)
    }
    const source = require(audioUrl)
    const initialStatus = {
      shouldPlay: isPlaying,
      volume,
      rate: audioRate,
      shouldCorrectPitch: true,
      pitchCorrectionQuality: Audio.PitchCorrectionQuality.Low
    }
    const { sound, status } = await Audio.Sound.createAsync(
      source,
      initialStatus,
      _onPlaybackStatusUpdate
    )
    setPlaybackInstance(sound)
    _updateScreenForLoading(false)
  }
like image 883
Sain8z K Avatar asked Jan 17 '26 08:01

Sain8z K


1 Answers

You are right, require is for static resources, not dynamic ones. According to documentation here, the source parameter can be one of three types.

  • source (object / number / Asset) -- The source of the sound. The following forms are supported:
    • A dictionary of the form { uri: string, headers?: { [string]: string }, overrideFileExtensionAndroid?: string }with a network URL pointing to a media file on the web, [...]
    • require('path/to/file') for an audio file asset in the source code directory.
    • An Asset object for an audio file asset.

You can use the first type of parameter for dynamic resources. You would do:

const source = { uri: audioUrl } where audioUrl can be a local resource as well: file:///path/to/resource

like image 89
Tiberiu Maran Avatar answered Jan 20 '26 02:01

Tiberiu Maran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!