This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
This is documentation for the next SDK version.
Expo MediaSession
A library that owns audio focus, the audio session, and Now Playing controls for the media libraries in an app.
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.
expo-audioandexpo-videodo not use this module yet. They still configure the audio session, audio focus, and the lock screen controls themselves. In an app that uses them, the audio policy and holds of this module do not change how they play, and a hold adds a second writer of the same 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
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
Configurable properties
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:
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:
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 alwaysdefault. - 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
beganwhile 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()
import ExpoMediaSession let use = MediaSessionManager.shared.beginUse(client: "my-player", requirements: SessionRequirements(mixing: .doNotMix)) try await use.activated() // ... use.end()
- On Android, call
close()to end aSessionUseor aSessionHold. On iOS, deinit ends them. awaitActivation()(Android) andactivated()(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, thenmixWithOthers. hold(client:)keeps the session active without requirements, like the JavaScriptholdSession.
Getting the session back
beginUseandholdactivate 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 sendsmediaSessionInterruptionEnded(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.
updateandsetPolicyreconfigure 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
beginUseandholdget 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.
mediaSessionDuckedandmediaSessionFocusLostare Android only. The Swift protocol declares them, but iOS never sends them.mediaSessionServicesReset()is iOS only.- Every
mediaSessionDucked(true)gets exactly onemediaSessionDucked(false). The Swift method ismediaSessionDucked(_:), and the Kotlin method ismediaSessionDucked(isDucked). - Every
mediaSessionInterruptionBegan(reason:)gets at most onemediaSessionInterruptionEnded(shouldResume:)before the nextmediaSessionInterruptionBegan(reason:). A permanent loss (mediaSessionFocusLost(transient: false)andmediaSessionInterruptionBegan(reason:)) may never get amediaSessionInterruptionEnded(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. ApplyplaysInSilentModeyourself.
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 sendmediaSessionDidFail(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:), andmediaSessionServicesReset(). It defersmediaSessionInterruptionEnded(shouldResume:)until writes resume. It sends nomediaSession(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 sendsmediaSessionDidFail(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 withshouldResume: true. If the user plays and then pauses that owner during the takeover, it stays paused. CallupdatefrompauseForTakeoverso the module sees the pause. - The defaults for
pauseForTakeoverandresumeAfterTakeoverhandle apauseand aplaycommand. - Commands go only to the top owner, and only for the kinds it offered. Do not offer
seekfor content that cannot seek. A live stream never showsseek. - 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
isPlayingconsistent with theelapsedTimeandplaybackRateof 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 aNowPlayingClaim. On iOS, deinit withdraws it. - On Android, the
NowPlayingInfoyou send drives the owner. An owner that implementsMediaPlayerOwnerexposes its Media3Playerinstead.
API
import * as MediaSession from 'expo-media-session';
Methods
Gets the current app-wide audio policy.
AudioPolicyKeeps 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.
voidReleases 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.
voidUpdates 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.
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
Adds a listener for failures to activate the audio session or to start the media playback service.
EventSubscriptionA subscription. Call remove() on it to stop listening.
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.
EventSubscriptionA subscription. Call remove() on it to stop listening.
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.
EventSubscriptionA subscription. Call remove() on it to stop listening.
Types
The module failed to activate the audio session or to start the media playback service.
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.
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:
Or object shaped as below:
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'
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'
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'