How to play background audio in react native using expo-av?

Viewed 4601

I am building a react native app using expo. I’m using ‘expo-av’.

I’m having trouble having my audio file play in the background.

I have the following but am still not able to get it to work when I switch my app to another app. I don't get any error; the music just stops in my app. Any advice on how to get this to work? Or is there somewhere else my code could be off?

  async componentDidMount() {
    try {
      await Audio.setAudioModeAsync({
        allowsRecordingIOS: false,
        interruptionModeIOS: Audio.INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS,
        // interruptionModeIOS: Audio.INTERRUPTION_MODE_IOS_DUCK_OTHERS,
        playsInSilentModeIOS: true,
        interruptionModeAndroid: Audio.INTERRUPTION_MODE_ANDROID_DUCK_OTHERS,
        shouldDuckAndroid: true,
        staysActiveInBackground: true,
        playThroughEarpieceAndroid: true
      })
      this.loadAudio();
    //   this.interval = setInterval(() => this.getStatus(), 1000);
    } catch (e) {
      console.log(e)
    }
  }
1 Answers

Everything works with such parameters:

Audio.setAudioModeAsync({
   allowsRecordingIOS: false,
   staysActiveInBackground: true,
   interruptionModeIOS: Audio.INTERRUPTION_MODE_IOS_DUCK_OTHERS,
   playsInSilentModeIOS: true,
   shouldDuckAndroid: true,
   interruptionModeAndroid: Audio.INTERRUPTION_MODE_ANDROID_DUCK_OTHERS,
   playThroughEarpieceAndroid: false
});

In package.json "expo-av": "^6.0.0",

In player:

componentDidMount() {
        Audio.setAudioModeAsync({
            allowsRecordingIOS: false,
            staysActiveInBackground: true,
            interruptionModeIOS: Audio.INTERRUPTION_MODE_IOS_DUCK_OTHERS,
            playsInSilentModeIOS: true,
            shouldDuckAndroid: true,
            interruptionModeAndroid: Audio.INTERRUPTION_MODE_ANDROID_DUCK_OTHERS,
            playThroughEarpieceAndroid: false
        });
        this._loadNewPlaybackInstance(true);
    }

async _loadNewPlaybackInstance(playing) {
        if (this.playbackInstance != null) {
            await this.playbackInstance.unloadAsync();
            this.playbackInstance = null;
        }
const source = { uri: 'http://music.ru/music.mp3' };

    const initialStatus = {
        shouldPlay: playing,
        rate: this.state.rate,
        shouldCorrectPitch: this.state.shouldCorrectPitch,
        volume: this.state.volume,
        isMuted: this.state.muted,
        isLooping: this.state.loopingType === LOOPING_TYPE_ONE
        // // UNCOMMENT THIS TO TEST THE OLD androidImplementation:
        // androidImplementation: 'MediaPlayer',
    };
    const {sound, status} = await Audio.Sound.createAsync(
        source,
        initialStatus,
        this._onPlaybackStatusUpdate
    );
    this.playbackInstance = sound;
Related