Writing

expo-audio stops playing in the background? Check who set the audio mode

By Mohamed Gado · · 4 min read

In Rafiq, my Quran app, people play a recitation, press home or lock the phone, and keep listening. One week that stopped working. Every player went quiet the moment the app left the screen: the Quran, the lectures, the daily dhikr. Nothing in the players had changed. The cause was a screen most people never open, calling setAudioModeAsync with shouldPlayInBackground: false. In expo-audio that call isn't about one player. It sets the mode for the whole app, and it stays set until something sets it again.

The symptom: every player pauses when the app goes to the background#

The report was simple: "audio stops when I leave the app, since the last release." It happened on every player, every time, on Android. The app's audio setup did ask for background playback, with shouldPlayInBackground: true at startup. That's the part that made it confusing, since the setting was right when the app opened.

The user's next message gave it away: "we meant to do that for the adhan only, not for any audio." Rafiq has a settings screen where you choose the muezzin for the call to prayer, and each voice has a play button so you can hear it first. That screen had its own audio setup.

The cause: setAudioModeAsync is process-wide#

The adhan sound picker started each preview like this:

// The picker's preview, before the fix
await setAudioModeAsync({
  playsInSilentMode: true,
  shouldPlayInBackground: false, // a 20 s preview shouldn't keep playing from a pocket
})
const player = createAudioPlayer(source)
player.play()

The intent was reasonable. A 20-second preview of a muezzin shouldn't keep playing after you put the phone away. But setAudioModeAsync doesn't configure that player. It configures the audio session for the whole process. On Android, expo-audio keeps a single shouldPlayInBackground field in its native module, and pauses every playing player when the app goes to the background while that field is false. From expo-audio's AudioModule.kt:

AsyncFunction("setAudioModeAsync") { mode: AudioMode ->
  shouldPlayInBackground = mode.shouldPlayInBackground
  // ...
}
 
OnActivityEntersBackground {
  if (!shouldPlayInBackground) {
    allPlayables.forEach { playable ->
      if (playable.isPlaying) { playable.isPaused = true; playable.pause() }
    }
  }
}

So one visit to Settings → adhan sound → play turned background playback off for every player in the app, and it stayed off until the next cold start, because nothing wrote the mode again after startup. Users who never opened that screen never saw the bug, which is why it looked random.

Why it took longer than it should have#

  • "Since the last release" sent me to the wrong diff. I read every audio change in the latest release looking for a new pause call. There wasn't one. The previews had shipped one release earlier. The report dated when people noticed, not when the code changed.
  • An earlier cleanup had missed this caller. A refactor had already moved three providers' setAudioModeAsync calls into one place. It missed the fourth caller because it was in a component, not a provider. The refactor looked where audio setup was expected to live instead of searching the whole repo for the function name.
  • A comment made the bug look deliberate. The line carried a comment explaining why the preview shouldn't play in the background. It read like a decision someone had thought through, so I skipped past it twice.

The same search turned up a second, quieter bug. When three providers each called setAudioModeAsync on mount, the last one to run won. React runs child effects before parent effects, so the outermost provider always wrote last. One provider's interruptionMode: 'mixWithOthers' had never taken effect.

The fix: one owner for the audio mode#

Two changes. First, the preview stopped touching the session. It ends its own sound instead: when the sheet closes, when the component unmounts, and when the app goes to the background.

useEffect(() => {
  const sub = AppState.addEventListener('change', (state) => {
    if (state === 'background') stopPreview()
  })
  return () => sub.remove()
}, [stopPreview])

Second, one hook now owns the audio mode, and it sets the mode again every time the app comes back to the foreground. Nothing in the app can read the mode back, so a stray write would otherwise stay in place without anyone noticing:

export function useAudioSessionMode(keepPlaying: boolean) {
  useEffect(() => {
    const apply = () =>
      setAudioModeAsync({
        playsInSilentMode: true,
        shouldPlayInBackground: keepPlaying,
        interruptionMode: 'doNotMix',
      }).catch(reportError)
    apply()
    const sub = AppState.addEventListener('change', (state) => {
      if (state === 'active') apply()
    })
    return () => sub.remove()
  }, [keepPlaying])
}

keepPlaying combines the user's background-audio setting with whether the full adhan is playing, so the call to prayer still plays through a locked screen even for someone who turned background audio off. It's one value, and one hook writes it.

A test pins the rule that this hook is the only caller of setAudioModeAsync. If a future screen adds its own call, the test fails, so the bug can't come back silently.

How to check your own app#

If expo-audio playback stops when your app goes to the background:

  1. Search the whole repo for setAudioModeAsync, not just your audio folder. Any call with shouldPlayInBackground: false affects every player.
  2. Check the config plugin. On iOS, background audio also needs the UIBackgroundModes audio entry, which the expo-audio plugin adds when you enable background playback.
  3. Count the callers. With more than one, the last write wins, and effect order decides which one that is.
  4. If a single sound must not play in the background, stop that sound yourself on an AppState background event. Leave the session alone.

Takeaways#

  • setAudioModeAsync sets the mode for every player in the app, not for the one you're about to create.
  • Give a process-wide setting exactly one caller, and pin that with a test.
  • When a refactor's goal is "one owner", search the repo for the function name instead of the folders you expect it in.
  • Set state you can't read back again on every return to the foreground.
  • A bug report that says "since the last release" tells you when someone noticed, not when the code changed.