This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.

Expo MediaSession

A library that owns audio focus, the audio session, and Now Playing controls for the media libraries in an app.

Android
iOS
Web

expo-media-session is the single owner of audio focus on Android and the app's audio session on iOS. It also owns the lock screen and notification media controls on both platforms. A media library that uses it requests what it needs instead of configuring the system itself. Two such libraries in one app then do not fight over the session.

Use the JavaScript API to set the app-wide audio policy, keep the session active between sounds, and listen for interruptions and route changes. Library authors use the native API.

Installation

Terminal
- npx expo install expo-media-session
- yarn expo install expo-media-session
- pnpm expo install expo-media-session
- bun expo install expo-media-session

If you are installing this in an existing React Native app, make sure to install expo in your project.

Configuration in app config

You can configure expo-media-session using its built-in config plugin if you use config plugins in your project (Continuous Native Generation (CNG)). The plugin allows you to configure properties that cannot be set at runtime and require building a new app binary to take effect. If your app does not use CNG, then you'll need to manually configure the library.

The library declares the media playback service on Android, so the Now Playing controls work without the plugin. Add the plugin to keep audio playing in the background.

Example app.json with config plugin

app.json
{ "expo": { "plugins": [ [ "expo-media-session", { "supportsBackgroundPlayback": true } ] ] } }

Configurable properties

NameDefaultDescription
supportsBackgroundPlaybackfalse

A boolean that determines whether audio can keep playing in the background. On Android, true adds the mediaPlayback foreground service type to the media playback service and adds the FOREGROUND_SERVICE and FOREGROUND_SERVICE_MEDIA_PLAYBACK permissions. On iOS, true adds the audio background mode. With false, Android still shows the media notification while a player owns it. It does not start a foreground service, so the system can stop playback in the background.

Are you using this library in an existing React Native app?

On Android, the library declares the media playback service. For background playback, add the foreground service type and permissions to AndroidManifest.xml. The manifest merger combines this entry with the library's entry, so keep android:exported set to false:

android/app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" /> <application> <service android:name="expo.modules.mediasession.service.MediaPlaybackService" android:exported="false" android:foregroundServiceType="mediaPlayback" /> </application>

The service reads its own declared foregroundServiceType to decide whether it can run in the foreground. Below Android 10 (API level 29), where service types do not exist, it follows the app's FOREGROUND_SERVICE_MEDIA_PLAYBACK permission instead.

On iOS, add the audio background mode to Info.plist if the app plays audio in the background:

ios/[app]/Info.plist
<key>UIBackgroundModes</key> <array> <string>audio</string> </array>

Usage

Set the audio policy

The audio policy applies to every media library that uses this module. Fields that you leave out keep their current values.

import { setAudioPolicyAsync } from 'expo-media-session'; await setAudioPolicyAsync({ interruptionMode: 'doNotMix' });

On iOS, the promise rejects when the merged policy is invalid, for example interruptionMode: 'duckOthers' with playsInSilentMode: false. The error message says which field to change.

Keep the session active between sounds

The module deactivates the session 1 second after the last library stops using it. In mixWithOthers mode on iOS, it never deactivates the session automatically. To keep the session active for longer, hold it with a key and release it with the same key. For example, hold it between the clips of a game level:

import { holdSession, releaseSession } from 'expo-media-session'; holdSession('level'); // ... releaseSession('level');

The module releases every hold when the JavaScript runtime reloads.

Listen for interruptions

import { useEffect } from 'react'; import { addInterruptionListener } from 'expo-media-session'; export function useInterruptionLog() { useEffect(() => { const subscription = addInterruptionListener(event => { if (event.type === 'began') { console.log('Interrupted:', event.reason); } else { console.log('Interruption ended, can resume:', event.shouldResume); } }); return () => subscription.remove(); }, []); }

The events differ between platforms:

  • On Android, the module learns about interruptions from audio focus. It requests no focus when the effective interruption mode is mixWithOthers, which is the default. The module calls the interruption listener only in the other modes, and only while a media library or a hold uses the session. The reason is always default.
  • On Android, the module calls the route change listener only with oldDeviceUnavailable, when the output device disconnects. Android does not report a device that connects.
  • On iOS, the module can call the interruption listener with began while no media library uses the session.
  • On web, the module never calls the listeners.

InterruptionReason and RouteChangeReason can get new values, so handle unknown values with a default case.

Web

On web, setAudioPolicyAsync stores the policy and does not change browser audio, and holds do nothing. The module never calls the interruption, route change, or activation error listeners.

For library authors

A media library uses the Swift and Kotlin API to get the session and to show Now Playing controls. Only this module writes the system state: AVAudioSession category and activation, Android audio focus, MPNowPlayingInfoCenter, MPRemoteCommandCenter targets, and the Media3 session service. A library that writes them directly breaks the other libraries in the app.

Uses and holds

Begin a use when the player starts. The call returns at once, and the module activates the session or requests audio focus in the background. Keep the token while the audio plays.

val use = MediaSessionManager.get(context).beginUse("my-player", SessionRequirements(mixing = MixingRequirement.DO_NOT_MIX)) use.awaitActivation() // A suspend function. Call it from a coroutine. // ... use.close()
  • On Android, call close() to end a SessionUse or a SessionHold. On iOS, deinit ends them.
  • awaitActivation() (Android) and activated() (iOS) wait for the first activation. They stay pending while writes are suspended, and on Android while a delayed focus grant is pending. They throw if the activation fails or the use ends first.
  • Requirements can only make the policy stricter. The mixing order is doNotMixPersistent, doNotMix, duckOthers, then mixWithOthers.
  • hold(client:) keeps the session active without requirements, like the JavaScript holdSession.

Getting the session back

  • beginUse and hold activate the session and request focus. The module also does this when it resumes writes, after an iOS media services reset, and when an iOS interruption ends and playback can resume. On iOS, it activates the session before it sends mediaSessionInterruptionEnded(shouldResume: true).
  • On iOS, the module activates the session again when the app returns to the foreground with a live use. The system can deactivate the session while the app is suspended. After an interruption begins, the module does not do this until it activates the session again, for example for a new use or hold, or when the interruption ends with shouldResume.
  • On iOS, when the last use ends, the module restores the policy configuration if a use changed the category, for example after a recording. Without an active use, the module makes only this write and the delayed deactivation.
  • update and setPolicy reconfigure the session. On Android, a reconfigure for an active use requests focus again with the new attributes. During a transient loss, the request waits until the system gives focus back.
  • After a permanent focus loss, only beginUse and hold get the session back. End the use and begin a new one, for example when the user presses play.

Observers

Add an observer with addObserver, and keep the returned ObserverRegistration. Every observer method has a default implementation, so implement only the events you need.

  • Observer methods run on the coordinator thread (Android) or the coordinator queue (iOS). Switch to your own isolation before you touch UI or player state.
  • mediaSessionDucked and mediaSessionFocusLost are Android only. The Swift protocol declares them, but iOS never sends them. mediaSessionServicesReset() is iOS only.
  • Every mediaSessionDucked(true) gets exactly one mediaSessionDucked(false). The Swift method is mediaSessionDucked(_:), and the Kotlin method is mediaSessionDucked(isDucked).
  • Every mediaSessionInterruptionBegan(reason:) gets at most one mediaSessionInterruptionEnded(shouldResume:) before the next mediaSessionInterruptionBegan(reason:). A permanent loss (mediaSessionFocusLost(transient: false) and mediaSessionInterruptionBegan(reason:)) may never get a mediaSessionInterruptionEnded(shouldResume:).
  • The module sends mediaSessionInterruptionEnded(shouldResume: true) only when live uses remain and it holds the session or focus again, or when the policy no longer needs focus (mixWithOthers).
  • mediaSessionSilentModeChanged(isSilent:) is Android only and reports the raw ringer state. Apply playsInSilentMode yourself.

Suspended writes

suspendWrites(reason:) stops all writes to the session until the matching resumeWrites(). While writes are suspended:

  • Android sends no focus events, and reports one net change after mediaSessionDidResumeWrites(). It can still send mediaSessionDidFail(error, client) when the media service or the foreground start fails, because the service is not a session write.
  • iOS still sends mediaSessionInterruptionBegan(reason:), mediaSessionRouteChanged(reason:), and mediaSessionServicesReset(). It defers mediaSessionInterruptionEnded(shouldResume:) until writes resume. It sends no mediaSession(didFail:client:), because it writes nothing.
  • A library that mirrors an interrupted state rebuilds it from the events after mediaSessionDidResumeWrites().

Platform differences

  • Android sends mediaSessionInterruptionBegan(reason:) only while a use is live. iOS can send it while no use is live.
  • On Android, a use that begins during a transient loss requests focus again. If the system grants focus, the interruption ends. If it delays the grant, awaitActivation() waits for it. If it refuses, the module sends mediaSessionDidFail(error, client). On iOS, the use gets no signal that it is interrupted.
  • iOS does not report the "app was suspended" interruption reason.

Now playing

Begin the session use first, then offer Now Playing. The module reads the live requirements when the offer arrives to decide whether the previous owner pauses. On iOS, the system shows the lock screen controls only for a session that does not mix with others. With the default mixWithOthers policy, begin the use with mixing: .doNotMix.

let claim = MediaSessionManager.shared.offerNowPlaying( player, info: NowPlayingInfo(title: "Episode 12", duration: 1800, elapsedTime: 0, playbackRate: 1), commands: [.play, .pause, .togglePlayPause, .seek] ) // On every play, pause, seek, rate, or metadata change: claim.update(NowPlayingInfo(title: "Episode 12", duration: 1800, elapsedTime: 42, playbackRate: 0)) // When the player stops: claim.withdraw()
  • A playing offer takes over at once. A paused offer takes over at once when the current owner is paused. When the current owner plays, a paused offer waits below it and takes over when it starts to play. An owner lower in the stack that starts to play also takes over. A pause keeps ownership. A withdraw removes that owner from anywhere in the stack.
  • A takeover pauses the previous owner, unless the effective interruption mode is mixWithOthers. When the newer owner withdraws, the previous owner resumes only if the takeover paused it. During an interruption, the resume waits until the interruption ends with shouldResume: true. If the user plays and then pauses that owner during the takeover, it stays paused. Call update from pauseForTakeover so the module sees the pause.
  • The defaults for pauseForTakeover and resumeAfterTakeover handle a pause and a play command.
  • Commands go only to the top owner, and only for the kinds it offered. Do not offer seek for content that cannot seek. A live stream never shows seek.
  • When you offer both skip and track commands, iOS shows next and previous instead of skip. iOS always answers commands with success.
  • The module can write Now Playing at any time, for example when another owner withdraws. Keep isPlaying consistent with the elapsedTime and playbackRate of your last update.
  • Owner callbacks run on the coordinator queue or thread. On iOS, the module switches to the main thread for the system writes, in order.
  • On Android, call close() to withdraw a NowPlayingClaim. On iOS, deinit withdraws it.
  • On Android, the NowPlayingInfo you send drives the owner. An owner that implements MediaPlayerOwner exposes its Media3 Player instead.

API

import * as MediaSession from 'expo-media-session';

Methods

MediaSession.getAudioPolicy()

Android
iOS
Web

Gets the current app-wide audio policy.

Returns:
AudioPolicy

MediaSession.holdSession(key)

Android
iOS
Web
ParameterTypeDescription
keystring

A name for the hold. The activationError event reports it as its client.


Keeps the audio session active, or audio focus held on Android, until you call releaseSession with the same key. Use it to keep the session active between two sounds. A second call with a key that is already held begins the hold again. Use that to activate the session again after an activationError or an interruption. The module releases every hold when the JavaScript runtime reloads.

The call returns at once. If the activation fails, the module sends an activationError event. On web, it does nothing.

Returns:
void

MediaSession.releaseSession(key)

Android
iOS
Web
ParameterTypeDescription
keystring

The key that was passed to holdSession.


Releases the hold that holdSession created with the same key. The module deactivates the session 1 second after the last use or hold ends, except in mixWithOthers mode on iOS, where it never deactivates the session automatically. An unknown key does nothing.

Returns:
void

MediaSession.setAudioPolicyAsync(update)

Android
iOS
Web
ParameterTypeDescription
updatePartial<AudioPolicy>

The fields of the audio policy to change.


Updates the app-wide audio policy. Fields that the update leaves out keep their current values. The module applies the new policy to the active session, and media libraries read it for every later use.

On web, the module stores the policy and does not change browser audio.

Returns:
Promise<void>

A promise that resolves when the module accepted the policy. On iOS, it rejects when the merged policy is invalid, for example interruptionMode: 'duckOthers' with playsInSilentMode: false. The error message says how to fix the policy.

Example

await setAudioPolicyAsync({ interruptionMode: 'doNotMix' });

Event subscriptions

MediaSession.addActivationErrorListener(listener)

Android
iOS
Web
ParameterType
listener(event: ActivationErrorEvent) => void

Adds a listener for failures to activate the audio session or to start the media playback service.

Returns:
EventSubscription

A subscription. Call remove() on it to stop listening.

MediaSession.addInterruptionListener(listener)

Android
iOS
Web
ParameterType
listener(event: InterruptionEvent) => void

Adds a listener for interruptions of the app's audio, such as a phone call or another app taking audio focus.

On Android, the module learns about interruptions from audio focus, and it requests no focus when the effective interruption mode is mixWithOthers, which is the default. The module calls the listener only in the other modes, and only while a media library or a hold uses the session.

On iOS, the module can send began while no media library uses the session.

On web, the module never calls the listener.

Returns:
EventSubscription

A subscription. Call remove() on it to stop listening.

MediaSession.addRouteChangeListener(listener)

Android
iOS
Web
ParameterType
listener(event: RouteChangeEvent) => void

Adds a listener for audio route changes, such as headphones connecting or disconnecting.

On Android, the module reports only oldDeviceUnavailable, when the output device disconnects. It does not report a device that connects.

On web, the module never calls the listener.

Returns:
EventSubscription

A subscription. Call remove() on it to stop listening.

Types

ActivationErrorEvent

Android
iOS
Web

The module failed to activate the audio session or to start the media playback service.

PropertyTypeDescription
clientstring

The client that requested the activation. For a hold, it is the key that was passed to holdSession. For any other client, it is the name that the media library registered. When the media playback service fails on Android, it is the ID of the Now Playing owner, or Now Playing when no owner exists.

messagestring

What failed, why, and what to do next.

AudioPolicy

Android
iOS
Web

The app-wide audio policy. The media libraries that use this module read it to configure audio focus on Android and the shared audio session on iOS.

PropertyTypeDescription
allowsRecording(optional)boolean

Whether the session allows recording. On iOS, this selects the playAndRecord category. On Android, the value is advisory: the module does not change the system audio state for it, and media libraries read it.

Default:false
interruptionMode(optional)InterruptionMode

How the app's audio behaves next to audio from other apps. A media library can request a stricter mode for one use, but never a looser one.

Default:'mixWithOthers'
playsInSilentMode(optional)boolean

Whether the app plays audio while the iOS silent switch is on. On Android, the module reports the ringer state to media libraries, and they apply this value.

Default:true
shouldRouteThroughEarpiece(optional)boolean

Whether audio plays through the earpiece instead of the speaker. On iOS, this only has an effect when allowsRecording is true (that is, the audio session category is playAndRecord). When false (the default), audio is routed through the speaker. On Android, this value has no effect.

Default:false

InterruptionEvent

Android
iOS
Web

An interruption of the app's audio began or ended.

An interruption that began can end with at most one ended event before the next began. A permanent loss of audio focus may never end.

Type: object shaped as below:

PropertyTypeDescription
reasonInterruptionReason

Why the system interrupted the app's audio.

type'began'

The interruption began.

Or object shaped as below:

PropertyTypeDescription
shouldResumeboolean

Whether the interrupted playback can resume. It is true only when a media library or a hold still uses the session and the session is active again.

type'ended'

The interruption ended.

InterruptionMode

Android
iOS
Web

Literal type: string

Describes how the app's audio behaves next to audio from other apps.

  • mixWithOthers: The app's audio plays together with other apps' audio.
  • duckOthers: Other apps lower their volume while the app plays.
  • doNotMix: Other apps pause while the app plays, and they can resume when it stops.
  • doNotMixPersistent: Other apps pause while the app plays, and they do not resume by themselves. On Android, the module requests permanent audio focus. On iOS, the module does not notify other apps when the session deactivates.

Acceptable values are: 'mixWithOthers' | 'doNotMix' | 'doNotMixPersistent' | 'duckOthers'

InterruptionReason

Android
iOS
Web

Literal type: string

Why the system interrupted the app's audio. The set can grow, so handle unknown values.

  • default: Another app or a system event, such as a call, took the audio. Android reports only this reason.
  • routeDisconnected: The output device disconnected (iOS 17 and later only).
  • builtInMicMuted: The built-in microphone was muted (iOS only).

Acceptable values are: 'default' | 'routeDisconnected' | 'builtInMicMuted'

RouteChangeEvent

Android
iOS
Web

The audio route changed.

PropertyTypeDescription
reasonRouteChangeReason

Why the route changed.

RouteChangeReason

Android
iOS
Web

Literal type: string

Why the audio route changed. The set can grow, so handle unknown values.

  • oldDeviceUnavailable: The previous output device, such as headphones, disconnected. Android reports only this reason.
  • newDeviceAvailable: A new output device connected (iOS only).
  • categoryChange: The session category changed (iOS only).
  • other: Any other route change (iOS only).

Acceptable values are: 'oldDeviceUnavailable' | 'newDeviceAvailable' | 'categoryChange' | 'other'

Reference version