Reference version

Expo 音频(expo-audio) iconExpo 音频(expo-audio)

一个提供 API 用于在应用中实现音频播放和录制的库。

Android
iOS
tvOS
Web
Included in Expo Go
Bundled version:
~55.0.0

For the complete documentation index, see llms.txt. Use this Use this file to discover all available pages.

expo-audio 是一个跨平台音频库,用于访问设备的原生音频能力。

Android 媒体格式支持文档涵盖了在 Android 上使用 Expo Player 时支持的格式。iOS 音频和视频格式文档列出了 Apple 设备支持的媒体格式。

请注意,如果耳机/Bluetooth 音频设备断开连接,音频会自动停止。

安装

Terminal
npx expo install expo-audio

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

在 app config 中配置

如果你在项目中使用 config plugins(Continuous Native Generation (CNG)),可以使用 expo-audio 内置的 config plugin 进行配置。该插件允许你配置一些无法在运行时设置、且需要重新构建新的应用二进制文件才会生效的属性。如果你的应用使用 CNG,那么你需要手动配置该库。

Example app.json with config plugin

app.json
{ "expo": { "plugins": [ [ "expo-audio", { "microphonePermission": "允许 $(PRODUCT_NAME) 访问你的麦克风。", "enableBackgroundPlayback": true, "enableBackgroundRecording": false } ] ] } }

Configurable properties

NameDefaultDescription
microphonePermission"允许 $(PRODUCT_NAME) 访问你的麦克风"
Only for:
iOS

用于设置 NSMicrophoneUsageDescription 权限消息的字符串。将其设为 false 会禁用该权限。

recordAudioAndroidtrue
Only for:
Android

一个布尔值,用于决定是否在 Android 上启用 RECORD_AUDIO 权限。

enableBackgroundRecordingfalse

一个布尔值,用于决定是否启用后台音频录制。在 Android 上,这会添加录制前台服务和权限,并在录制期间显示一条持续存在的通知。在 iOS 上,这会添加 audio 后台模式。**注意:**后台录制可能会显著影响电池续航。

enableBackgroundPlaybacktrue

一个布尔值,用于决定是否启用后台音频播放。在 Android 上,这会添加媒体播放前台服务,并允许你显示锁屏控制,这是持续后台播放所必需的。在 iOS 上,这会添加 audio 后台模式。

用法

播放声音

播放声音
import { View, StyleSheet, Button } from 'react-native'; import { useAudioPlayer } from 'expo-audio'; const audioSource = require('./assets/Hello.mp3'); export default function App() { const player = useAudioPlayer(audioSource); return ( <View style={styles.container}> <Button title="播放声音" onPress={() => player.play()} /> <Button title="重新播放声音" onPress={() => { player.seekTo(0); player.play(); }} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', backgroundColor: '#ecf0f1', padding: 10, }, });

录制声音

录制声音
import { useState, useEffect } from 'react'; import { View, StyleSheet, Button } from 'react-native'; import { useAudioRecorder, AudioModule, RecordingPresets, setAudioModeAsync, useAudioRecorderState, } from 'expo-audio'; export default function App() { const audioRecorder = useAudioRecorder(RecordingPresets.HIGH_QUALITY); const recorderState = useAudioRecorderState(audioRecorder); const record = async () => { await audioRecorder.prepareToRecordAsync(); audioRecorder.record(); }; const stopRecording = async () => { // 录音文件将可通过 `audioRecorder.uri` 获取。 await audioRecorder.stop(); }; useEffect(() => { (async () => { const status = await AudioModule.requestRecordingPermissionsAsync(); if (!status.granted) { Alert.alert('访问麦克风的权限被拒绝'); } setAudioModeAsync({ playsInSilentMode: true, allowsRecording: true, }); })(); }, []); return ( <View style={styles.container}> <Button title={recorderState.isRecording ? '停止录音' : '开始录音'} onPress={recorderState.isRecording ? stopRecording : record} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', backgroundColor: '#ecf0f1', padding: 10, }, });

在后台播放音频

后台音频播放允许你的应用在进入后台或设备屏幕锁定时继续播放音频。

配置

要启用后台音频播放,请在你的 app config 中使用 config plugin:

app.json
{ "expo": { "plugins": [ [ "expo-audio", { "enableBackgroundPlayback": true } ] ] } }

上述配置会自动配置所需的原生设置:

  • Android
    添加 FOREGROUND_SERVICEFOREGROUND_SERVICE_MEDIA_PLAYBACK 权限。同时在应用的 AndroidManifest.xml 中声明一个媒体播放前台服务 (AudioControlsService)。
  • iOS
    添加 audio UIBackgroundMode 能力

用法

在使用 config plugin 配置完应用后,你需要:

  1. 配置音频会话 以允许后台播放
  2. 启用锁屏控制(在 Android 上持续后台播放是必需的)
import { View, Button } from 'react-native'; import { useAudioPlayer, setAudioModeAsync } from 'expo-audio'; import { useEffect } from 'react'; export default function AudioPlayerScreen() { const audioSource = require('./assets/audio.mp3'); const player = useAudioPlayer(audioSource); useEffect(() => { // 为后台播放配置音频会话 setAudioModeAsync({ playsInSilentMode: true, shouldPlayInBackground: true, interruptionMode: 'doNotMix', }); }, []); const handlePlay = () => { // 使用元数据启用锁屏控制 player.setActiveForLockScreen(true, { title: '我的音频标题', artist: '艺人名称', albumTitle: '专辑名称', artworkUrl: 'https://example.com/artwork.jpg', // 可选 }); // 开始播放 - 这将继续在后台运行 player.play(); }; const handleStop = () => { player.pause(); // 可选:完成后禁用锁屏控制 player.setActiveForLockScreen(false); }; return ( <View> <Button title="播放" onPress={handlePlay} /> <Button title="停止" onPress={handleStop} /> </View> ); }
Android

注意:在 Android 上,你必须使用 setActiveForLockScreen 启用锁屏控制,才能实现持续后台播放。否则,音频将在大约 3 分钟的后台播放后停止(这是操作系统限制)。请确保正确地配置 config plugin

  • 通知栏中会出现带有播放控制的媒体通知
  • 音频会在后台无限期播放
  • 用户可以通过锁屏和通知控制播放
  • 前台服务会在播放期间保持播放进程存活
iOS

在 iOS 上,一旦音频会话配置为 shouldPlayInBackground: true,音频播放就会在后台无缝继续。锁屏控制是可选的,但它们通过在锁屏和控制中心提供播放控制来提升用户体验。

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

如果你没有使用 Continuous Native Generation(CNG)(也就是你在手动使用原生 androidios 项目),那么你需要为后台播放配置以下内容:

  • 对于 Android,添加到 android/app/src/main/AndroidManifest.xml

    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.audio.service.AudioControlsService" android:exported="false" android:foregroundServiceType="mediaPlayback"> <intent-filter> <action android:name="androidx.media3.session.MediaSessionService" /> </intent-filter> </service> </application>
  • 对于 iOS,添加到 ios/YourApp/Info.plist

    ios/YourApp/Info.plist
    <key>UIBackgroundModes</key> <array> <string>audio</string> </array>

在后台录制音频

警告 后台录制可能会显著影响电池续航。仅在你的应用功能确实需要时才启用它。

后台音频录制允许你的应用在进入后台或设备屏幕锁定时继续录制。

要启用后台录制,请在你的 app config 中使用 config plugin:

app.json
{ "expo": { "plugins": [ [ "expo-audio", { "microphonePermission": "允许 $(PRODUCT_NAME) 录制音频。", "enableBackgroundRecording": true } ] ] } }

上述配置会自动配置所需的原生设置:

  • Android
    添加 FOREGROUND_SERVICE, FOREGROUND_SERVICE_MICROPHONEPOST_NOTIFICATIONS 权限。同时在应用的 AndroidManifest.xml 中声明一个音频 录制前台服务。
  • iOS
    添加 audio UIBackgroundMode 能力
Are you using this library in an existing React Native app?

如果你没有使用 Continuous Native Generation(CNG)(也就是你在手动使用原生 androidios 项目),那么你需要在原生项目中配置以下权限:

  • 对于 Android,添加到 android/app/src/main/AndroidManifest.xml

    android/app/src/main/AndroidManifest.xml
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
  • 对于 iOS,添加到 ios/YourApp/Info.plist

    ios/YourApp/Info.plist
    <key>UIBackgroundModes</key> <array> <string>audio</string> </array>

用法

配置完应用后,可在运行时使用 setAudioModeAsync 启用后台录制:

import { setAudioModeAsync, useAudioRecorder, RecordingPresets } from 'expo-audio'; await setAudioModeAsync({ playsInSilentMode: true, allowsRecording: true, allowsBackgroundRecording: true, }); const recorder = useAudioRecorder(RecordingPresets.HIGH_QUALITY); await recorder.prepareToRecordAsync(); await recorder.record(); // 录音会在后台继续
Android

在 Android 上,后台录制需要前台服务,它会显示一条带有“正在录制音频”文本和停止按钮的持续通知。录制进行时,这条通知无法被关闭,录制停止后会自动消失。

iOS

在 iOS 上,当应用处于后台或屏幕锁定时,后台录制会无缝继续。除系统状态栏之外,不会向应用用户显示任何额外通知或指示。

直接使用 AudioPlayer

在大多数情况下,请使用 useAudioPlayer 钩子来创建 AudioPlayer 实例。它会管理播放器的生命周期,并在组件卸载时确保正确释放。不过,在某些高级用例中,你可能需要创建一个超出组件生命周期仍然存在的 AudioPlayer。 在这种情况下,请使用 createAudioPlayer 函数。你需要了解这种方式带来的风险,因为当播放器不再需要时,调用 release() 方法是你的责任。如果处理不当,这种方式可能导致内存泄漏。

import { createAudioPlayer } from 'expo-audio'; const player = createAudioPlayer(audioSource);

Web 使用说明

  • Chrome 上的一个 MediaRecorder 问题会生成缺少时长元数据的 WebM 文件。查看公开的 Chromium 问题
  • MediaRecorder 的编码选项和其他配置在不同浏览器之间并不一致。在你的应用中使用诸如 kbumsik/opus-media-recorderai/audio-recorder-polyfill 这样的 polyfill 会改善你的体验。传递给 prepareToRecordAsync 的任何选项都会直接传递给 MediaRecorder API,因此也会传递给 polyfill。
  • Web 浏览器要求站点必须通过安全方式提供,才能监听麦克风。更多详情请参见 MediaDevices getUserMedia() security

API

import { useAudioPlayer, useAudioRecorder } from 'expo-audio';

Constants

Audio.RecordingPresets

Android
iOS
tvOS
Web

Type: { HIGH_QUALITY: RecordingOptions, LOW_QUALITY: RecordingOptions }

Constant which contains definitions of the two preset examples of RecordingOptions, as implemented in the Audio SDK.

HIGH_QUALITY

RecordingPresets.HIGH_QUALITY = { extension: '.m4a', sampleRate: 44100, numberOfChannels: 2, bitRate: 128000, android: { outputFormat: 'mpeg4', audioEncoder: 'aac', }, ios: { outputFormat: IOSOutputFormat.MPEG4AAC, audioQuality: AudioQuality.MAX, linearPCMBitDepth: 16, linearPCMIsBigEndian: false, linearPCMIsFloat: false, }, web: { mimeType: 'audio/webm', bitsPerSecond: 128000, }, };

LOW_QUALITY

RecordingPresets.LOW_QUALITY = { extension: '.m4a', sampleRate: 44100, numberOfChannels: 2, bitRate: 64000, android: { extension: '.3gp', outputFormat: '3gp', audioEncoder: 'amr_nb', }, ios: { audioQuality: AudioQuality.MIN, outputFormat: IOSOutputFormat.MPEG4AAC, linearPCMBitDepth: 16, linearPCMIsBigEndian: false, linearPCMIsFloat: false, }, web: { mimeType: 'audio/webm', bitsPerSecond: 128000, }, };

Hooks

useAudioPlayer(source, options)

Android
iOS
tvOS
Web
ParameterTypeDescription
source(optional)AudioSource

The audio source to load. Can be a local asset via require(), a remote URL, or null for no initial source.

Default:null
options(optional)AudioPlayerOptions

Audio player configuration options.

Default:{}

Creates an AudioPlayer instance that automatically releases when the component unmounts.

This hook manages the player's lifecycle and ensures it's properly disposed when no longer needed. The player will start loading the audio source immediately upon creation.

Returns:
AudioPlayer

An AudioPlayer instance that's automatically managed by the component lifecycle.

Example

import { useAudioPlayer } from 'expo-audio'; function MyComponent() { const player = useAudioPlayer(require('./sound.mp3')); return ( <Button title="Play" onPress={() => player.play()} /> ); }

Example

import { useAudioPlayer } from 'expo-audio'; function MyComponent() { const player = useAudioPlayer('https://example.com/audio.mp3', { updateInterval: 1000, downloadFirst: true, }); return ( <Button title="Play" onPress={() => player.play()} /> ); }

useAudioPlayerStatus(player)

Android
iOS
tvOS
Web
ParameterTypeDescription
playerAudioPlayer

The AudioPlayer instance to monitor.


Hook that provides real-time playback status updates for an AudioPlayer.

This hook automatically subscribes to playback status changes and returns the current status. The status includes information about playback state, current time, duration, loading state, and more.

Returns:
AudioStatus

The current AudioStatus object containing playback information.

Example

import { useAudioPlayer, useAudioPlayerStatus } from 'expo-audio'; function PlayerComponent() { const player = useAudioPlayer(require('./sound.mp3')); const status = useAudioPlayerStatus(player); return ( <View> <Text>Playing: {status.playing ? 'Yes' : 'No'}</Text> <Text>Current Time: {status.currentTime}s</Text> <Text>Duration: {status.duration}s</Text> </View> ); }

useAudioPlaylist(options)

Android
iOS
tvOS
Web
ParameterTypeDescription
options(optional)AudioPlaylistOptions

Audio playlist configuration options including initial sources and loop mode.

Default:{}

Creates an AudioPlaylist instance that automatically releases when the component unmounts.

This hook manages the playlist's lifecycle and ensures it's properly disposed when no longer needed. An audio playlist allows you to manage a collection of audio sources with gapless playback support.

An AudioPlaylist instance that's automatically managed by the component lifecycle.

Example

import { useAudioPlaylist } from 'expo-audio'; function PlaylistPlayer() { const playlist = useAudioPlaylist({ sources: [ require('./track1.mp3'), require('./track2.mp3'), 'https://example.com/track3.mp3', ], loop: 'all', }); return ( <View> <Text>Track {playlist.currentIndex + 1} of {playlist.trackCount}</Text> <Button title="Previous" onPress={() => playlist.previous()} /> <Button title={playlist.playing ? 'Pause' : 'Play'} onPress={() => playlist.playing ? playlist.pause() : playlist.play()} /> <Button title="Next" onPress={() => playlist.next()} /> </View> ); }

useAudioPlaylistStatus(playlist)

Android
iOS
tvOS
Web
ParameterTypeDescription
playlistAudioPlaylist

The AudioPlaylist instance to monitor.


Hook that provides real-time status updates for an AudioPlaylist.

This hook automatically subscribes to playlist status changes and returns the current status. The status includes information about the current track, playback state, and playlist position.

The current AudioPlaylistStatus object containing playlist and playback information.

Example

import { useAudioPlaylist, useAudioPlaylistStatus } from 'expo-audio'; function PlaylistStatusDisplay() { const playlist = useAudioPlaylist({ sources: [require('./track1.mp3')] }); const status = useAudioPlaylistStatus(playlist); return ( <View> <Text>Track: {status.currentIndex + 1} / {status.trackCount}</Text> <Text>Time: {status.currentTime}s / {status.duration}s</Text> <Text>Playing: {status.playing ? 'Yes' : 'No'}</Text> </View> ); }

useAudioRecorder(options, statusListener)

Android
iOS
tvOS
Web
ParameterTypeDescription
optionsRecordingOptions

Recording configuration options including format, quality, sample rate, etc.

statusListener(optional)(status: RecordingStatus) => void

Optional callback function that receives recording status updates.


Hook that creates an AudioRecorder instance for recording audio.

This hook manages the recorder's lifecycle and ensures it's properly disposed when no longer needed. The recorder is automatically prepared with the provided options and can be used to record audio.

An AudioRecorder instance that's automatically managed by the component lifecycle.

Example

import { useAudioRecorder, RecordingPresets } from 'expo-audio'; function RecorderComponent() { const recorder = useAudioRecorder( RecordingPresets.HIGH_QUALITY, (status) => console.log('Recording status:', status) ); const startRecording = async () => { await recorder.prepareToRecordAsync(); recorder.record(); }; return ( <Button title="Start Recording" onPress={startRecording} /> ); }

useAudioRecorderState(recorder, interval)

Android
iOS
tvOS
Web
ParameterTypeDescription
recorderAudioRecorder

The AudioRecorder instance to monitor.

interval(optional)number

How often (in milliseconds) to poll the recorder's status. Defaults to 500ms.

Default:500

Hook that provides real-time recording state updates for an AudioRecorder.

This hook polls the recorder's status at regular intervals and returns the current recording state. Use this when you need to monitor the recording status without setting up a status listener.

The current RecorderState containing recording information.

Example

import { useAudioRecorder, useAudioRecorderState, RecordingPresets } from 'expo-audio'; function RecorderStatusComponent() { const recorder = useAudioRecorder(RecordingPresets.HIGH_QUALITY); const state = useAudioRecorderState(recorder); return ( <View> <Text>Recording: {state.isRecording ? 'Yes' : 'No'}</Text> <Text>Duration: {Math.round(state.durationMillis / 1000)}s</Text> <Text>Can Record: {state.canRecord ? 'Yes' : 'No'}</Text> </View> ); }

useAudioSampleListener(player, listener)

Android
iOS
tvOS
Web
ParameterTypeDescription
playerAudioPlayer

The AudioPlayer instance to sample audio from.

listener(data: AudioSample) => void

Function called with each audio sample containing waveform data.


Hook that sets up audio sampling for an AudioPlayer and calls a listener with audio data.

This hook enables audio sampling on the player (if supported) and subscribes to audio sample updates. Audio sampling provides real-time access to audio waveform data for visualization or analysis.

Note: Audio sampling requires RECORD_AUDIO permission on Android and is not supported on all platforms.

Returns:
void

Example

import { useEffect } from 'react'; import { useAudioPlayer, useAudioSampleListener, requestRecordingPermissionsAsync } from 'expo-audio'; function AudioVisualizerComponent() { const player = useAudioPlayer(require('./music.mp3')); // if required on Android, request recording permissions useEffect(() => { async function requestPermission() { const { granted } = await requestRecordingPermissionsAsync(); if (granted) { console.log("Permission granted"); } } requestPermission(); }, []); useAudioSampleListener(player, (sample) => { // Use sample.channels array for audio visualization console.log('Audio sample:', sample.channels[0].frames); }); return <AudioWaveform player={player} />; }

Classes

AudioPlayer

Android
iOS
tvOS
Web

Type: Class extends SharedObject<AudioEvents>

AudioPlayer Properties

currentTime

Android
iOS
tvOS
Web
Type: number

The current position through the audio item in seconds.

duration

Android
iOS
tvOS
Web
Type: number

The total duration of the audio in seconds.

id

Android
iOS
tvOS
Web
Type: string

Unique identifier for the player object.

isAudioSamplingSupported

Android
iOS
tvOS
Web
Type: boolean

Boolean value indicating whether audio sampling is supported on the platform.

isBuffering

Android
iOS
tvOS
Web
Type: boolean

Boolean value indicating whether the player is buffering.

isLoaded

Android
iOS
tvOS
Web
Type: boolean

Boolean value indicating whether the player is finished loading.

loop

Android
iOS
tvOS
Web
Type: boolean

Boolean value indicating whether the player is currently looping.

muted

Android
iOS
tvOS
Web
Type: boolean

Boolean value indicating whether the player is currently muted.

paused

Android
iOS
tvOS
Web
Type: boolean

Boolean value indicating whether the player is currently paused.

playbackRate

Android
iOS
tvOS
Web
Type: number

The current playback rate of the audio. It accepts different values depending on the platform:

  • Android: 0.1 to 2.0
  • iOS: 0.0 to 2.0
  • Web: Follows browser implementation

Example

import { useAudioPlayer } from 'expo-audio'; export default function App() { const player = useAudioPlayer(source); // Normal playback speed player.playbackRate = 1.0; // Slow motion (half speed) player.playbackRate = 0.5; // Fast playback (1.5x speed) player.playbackRate = 1.5; // Maximum speed on mobile player.playbackRate = 2.0; }

playing

Android
iOS
tvOS
Web
Type: boolean

Boolean value indicating whether the player is currently playing.

shouldCorrectPitch

Android
iOS
tvOS
Web
Type: boolean

A boolean describing if we are correcting the pitch for a changed rate.

volume

Android
iOS
tvOS
Web
Type: number

The current volume of the audio.

Range: 0.0 to 1.0. For example, 0.0 is completely silent (0%), 0.5 is half volume (50%), and 1.0 is full volume (100%).

Example

import { useAudioPlayer } from 'expo-audio'; export default function App() { const player = useAudioPlayer(source); // Mute the audio player.volume = 0.0; // Set volume to 50% player.volume = 0.5; // Set to full volume player.volume = 1.0; }

AudioPlayer Methods

clearLockScreenControls()

Android
iOS
tvOS
Web

Removes this player from lock screen controls if it's currently active. This will clear the lock screen's now playing info.

Returns:
void

pause()

Android
iOS
tvOS
Web

Pauses the player.

Returns:
void

play()

Android
iOS
tvOS
Web

Start playing audio.

Returns:
void

remove()

Android
iOS
tvOS
Web

Remove the player from memory to free up resources.

Returns:
void

replace(source)

Android
iOS
tvOS
Web
ParameterType
sourceAudioSource

Replaces the current audio source with a new one.

Returns:
void

seekTo(seconds, toleranceMillisBefore, toleranceMillisAfter)

Android
iOS
tvOS
Web
ParameterTypeDescription
secondsnumber

The number of seconds to seek by.

toleranceMillisBefore(optional)number

The tolerance allowed before the requested seek time, in milliseconds. iOS only.

toleranceMillisAfter(optional)number

The tolerance allowed after the requested seek time, in milliseconds. iOS only.


Seeks the playback by the given number of seconds.

Returns:
Promise<void>

setActiveForLockScreen(active, metadata, options)

Android
iOS
tvOS
Web
ParameterTypeDescription
activeboolean

Whether this player should be active for lock screen controls.

metadata(optional)AudioMetadata

Optional metadata to display on the lock screen (title, artist, album, artwork).

options(optional)AudioLockScreenOptions

Optional configuration to configure the lock screen controls.


Sets or removes this audio player as the active player for lock screen controls. Only one player can control the lock screen at a time.

Note: For lock screen controls to work correctly, interruptionMode must be set to doNotMix using setAudioModeAsync. Without this, the OS might not associate lock screen controls with your player.

Returns:
void

setPlaybackRate(rate, pitchCorrectionQuality)

Android
iOS
tvOS
Web
ParameterTypeDescription
ratenumber

The playback rate of the audio. See playbackRate property for detailed range information.

pitchCorrectionQuality(optional)PitchCorrectionQuality

The quality of the pitch correction.


Sets the current playback rate of the audio.

Returns:
void

updateLockScreenMetadata(metadata)

Android
iOS
tvOS
Web
ParameterTypeDescription
metadataAudioMetadata

The metadata to display (title, artist, album, artwork).


Updates the metadata displayed on the lock screen for this player. This method only has an effect if this player is currently active for lock screen controls.

Returns:
void

AudioPlaylist

Android
iOS
tvOS
Web

Type: Class extends SharedObject<AudioPlaylistEvents>

AudioPlaylist Properties

currentIndex

Android
iOS
tvOS
Web
Read Only • Type: number

Index of the currently playing track in the playlist.

currentTime

Android
iOS
tvOS
Web
Type: number

Current playback position in seconds.

duration

Android
iOS
tvOS
Web
Type: number

Duration of the current track in seconds.

id

Android
iOS
tvOS
Web
Type: string

Unique identifier for the playlist instance.

isBuffering

Android
iOS
tvOS
Web
Type: boolean

Boolean value indicating whether the playlist is buffering.

isLoaded

Android
iOS
tvOS
Web
Type: boolean

Boolean value indicating whether the current track has finished loading.

loop

Android
iOS
tvOS
Web

Current loop mode.

muted

Android
iOS
tvOS
Web
Type: boolean

Boolean value indicating whether the playlist is currently muted.

playbackRate

Android
iOS
tvOS
Web
Type: number

Current playback rate (1.0 = normal speed).

playing

Android
iOS
tvOS
Web
Type: boolean

Boolean value indicating whether the playlist is currently playing.

sources

Android
iOS
tvOS
Web
Read Only • Type: AudioSourceInfo[]

The audio sources currently in the playlist.

trackCount

Android
iOS
tvOS
Web
Read Only • Type: number

Total number of tracks in the playlist.

volume

Android
iOS
tvOS
Web
Type: number

Current volume (0.0 to 1.0).

AudioPlaylist Methods

add(source)

Android
iOS
tvOS
Web
ParameterTypeDescription
sourceAudioSource

The audio source to add.


Add a track to the end of the playlist.

Returns:
void

clear()

Android
iOS
tvOS
Web

Clear all tracks from the playlist.

Returns:
void

destroy()

Android
iOS
tvOS
Web

Destroy the playlist and free up resources.

Returns:
void

insert(source, index)

Android
iOS
tvOS
Web
ParameterTypeDescription
sourceAudioSource

The audio source to insert.

indexnumber

The position to insert at.


Insert a track at a specific position in the playlist.

Returns:
void

next()

Android
iOS
tvOS
Web

Skip to the next track in the playlist. If at the end of the playlist and loop mode is 'all', wraps to the first track. If loop mode is 'none' and at the end, does nothing.

Returns:
void

pause()

Android
iOS
tvOS
Web

Pause playback.

Returns:
void

play()

Android
iOS
tvOS
Web

Start playing the current track in the playlist.

Returns:
void

previous()

Android
iOS
tvOS
Web

Skip to the previous track in the playlist. If at the beginning of the playlist and loop mode is 'all', wraps to the last track. If loop mode is 'none' and at the beginning, does nothing.

Returns:
void

remove(index)

Android
iOS
tvOS
Web
ParameterTypeDescription
indexnumber

The index of the track to remove.


Remove a track from the playlist by index.

Returns:
void

seekTo(seconds)

Android
iOS
tvOS
Web
ParameterTypeDescription
secondsnumber

The position to seek to.


Seeks the playback to a specific position in seconds.

Returns:
Promise<void>

skipTo(index)

Android
iOS
tvOS
Web
ParameterTypeDescription
indexnumber

The index of the track to skip to.


Skip to a specific track in the playlist by index.

Returns:
void

AudioRecorder

Android
iOS
tvOS
Web

Type: Class extends SharedObject<RecordingEvents>

AudioRecorder Properties

currentTime

Android
iOS
tvOS
Web
Type: number

The current length of the recording, in seconds.

id

Android
iOS
tvOS
Web
Type: string

Unique identifier for the recorder object.

isRecording

Android
iOS
tvOS
Web
Type: boolean

Boolean value indicating whether the recording is in progress.

uri

Android
iOS
tvOS
Web
Literal type: union

The uri of the recording.

Acceptable values are: string | null

AudioRecorder Methods

getAvailableInputs()

Android
iOS
tvOS
Web

Returns a list of available recording inputs. This method can only be called if the Recording has been prepared.

A Promise that is fulfilled with an array of RecordingInput objects.

getCurrentInput()

Android
iOS
tvOS
Web

Returns the currently-selected recording input. This method can only be called if the Recording has been prepared.

A Promise that is fulfilled with a RecordingInput object.

getStatus()

Android
iOS
tvOS
Web

Status of the current recording.

pause()

Android
iOS
tvOS
Web

Pause the recording.

Returns:
void

prepareToRecordAsync(options)

Android
iOS
tvOS
Web
ParameterType
options(optional)Partial<RecordingOptions>

Prepares the recording for recording.

Returns:
Promise<void>

record(options)

Android
iOS
tvOS
Web
ParameterTypeDescription
options(optional)RecordingStartOptions

Optional recording configuration options.


Starts the recording.

Returns:
void

Deprecated: Use record({ forDuration: seconds }) instead.

recordForDuration(seconds)

Android
iOS
tvOS
Web
ParameterTypeDescription
secondsnumber

The time in seconds to stop recording at.


Stops the recording once the specified time has elapsed.

Returns:
void

setInput(inputUid)

Android
iOS
tvOS
Web
ParameterTypeDescription
inputUidstring

The uid of a RecordingInput.


Sets the current recording input.

Returns:
void

A Promise that is resolved if successful or rejected if not.

Deprecated: Use record({ atTime: seconds }) instead.

startRecordingAtTime(seconds)

Android
iOS
tvOS
Web
ParameterTypeDescription
secondsnumber

The time in seconds to start recording at.


Starts the recording at the given time.

Returns:
void

stop()

Android
iOS
tvOS
Web

Stop the recording.

Returns:
Promise<void>

Methods

Audio.clearAllPreloadedSources()

Android
iOS
tvOS
Web

Releases all preloaded audio sources to free memory.

Returns:
Promise<void>

Audio.clearPreloadedSource(source)

Android
iOS
tvOS
Web
ParameterTypeDescription
sourceAudioSource

The audio source to release. Must match the source previously passed to preload().


Releases a specific preloaded audio source to free memory.

Returns:
Promise<void>

Audio.createAudioPlayer(source, options)

Android
iOS
tvOS
Web
ParameterTypeDescription
source(optional)AudioSource

The audio source to load.

Default:null
options(optional)AudioPlayerOptions

Audio player configuration options.

Default:{}

Creates an instance of an AudioPlayer that doesn't release automatically.

For most use cases you should use the useAudioPlayer hook instead. See the Using the AudioPlayer directly section for more details.
Returns:
AudioPlayer

Audio.createAudioPlaylist(options)

Android
iOS
tvOS
Web
ParameterTypeDescription
options(optional)AudioPlaylistOptions

Audio playlist configuration options.

Default:{}

Creates an instance of an AudioPlaylist that doesn't release automatically.

For most use cases you should use the useAudioPlaylist hook instead.

Audio.getPreloadedSources()

Android
iOS
tvOS
Web

Returns the URIs of all currently preloaded audio sources.

On iOS, sources are removed from this list when consumed by useAudioPlayer(), createAudioPlayer(), or player.replace(). On Android and web, sources remain until explicitly cleared with clearPreloadedSource() / clearAllPreloadedSources().

Returns:
Promise<string[]>

An array of URI strings for sources currently in the preload cache.

Audio.getRecordingPermissionsAsync()

Android
iOS
tvOS
Web

Checks the current status of recording permissions without requesting them.

This function returns the current permission status for microphone access without triggering a permission request dialog. Use this to check permissions before deciding whether to call requestRecordingPermissionsAsync().

Returns:
Promise<PermissionResponse>

A Promise that resolves to a PermissionResponse object containing the current permission status.

Example

import { getRecordingPermissionsAsync, requestRecordingPermissionsAsync } from 'expo-audio'; const ensureRecordingPermissions = async () => { const { status } = await getRecordingPermissionsAsync(); if (status !== 'granted') { // Permission not granted, request it const { granted } = await requestRecordingPermissionsAsync(); return granted; } return true; // Already granted };

Audio.preload(source, options)

Android
iOS
tvOS
Web
ParameterTypeDescription
sourceAudioSource

The audio source to preload. Can be a URL string, a local asset via require(), or an audio source object.

options(optional)PreloadOptions

Optional configuration for preloading behavior.

Default:{}

Preloads an audio source for near-instant playback later.

This should be called in module scope, before any React components render. When the source is later used with useAudioPlayer(), createAudioPlayer(), or player.replace(), playback begins with minimal delay.

Returns:
Promise<void>

Example

import { preload, useAudioPlayer } from 'expo-audio'; const track1 = 'https://example.com/track1.mp3'; const track2 = 'https://example.com/track2.mp3'; // Preload at module scope — starts buffering immediately preload(track1); preload(track2, { preferredForwardBufferDuration: 20 }); export default function App() { const player = useAudioPlayer(track1); // Playback starts near-instantly because the source was preloaded return <Button title="Play" onPress={() => player.play()} />; }

Audio.requestNotificationPermissionsAsync()

Android
iOS
tvOS
Web

Requests permission to post notifications on Android.

This is required for showing media playback controls in the notification shade. This function is only available on Android and will throw on other platforms.

Returns:
Promise<PermissionResponse>

A Promise that resolves to a PermissionResponse object containing the permission status.

Example

import { requestNotificationPermissionsAsync } from 'expo-audio'; const checkPermissions = async () => { const { status, granted } = await requestNotificationPermissionsAsync(); if (granted) { console.log('Notification permission granted'); } else { console.log('Notification permission denied:', status); } };

Audio.requestRecordingPermissionsAsync()

Android
iOS
tvOS
Web

Requests permission to record audio from the microphone.

This function prompts the user for microphone access permission, which is required for audio recording functionality. On iOS, this will show the system permission dialog. On Android, this requests the RECORD_AUDIO permission.

Returns:
Promise<PermissionResponse>

A Promise that resolves to a PermissionResponse object containing the permission status.

Example

import { requestRecordingPermissionsAsync } from 'expo-audio'; const checkPermissions = async () => { const { status, granted } = await requestRecordingPermissionsAsync(); if (granted) { console.log('Recording permission granted'); } else { console.log('Recording permission denied:', status); } };

Audio.setAudioModeAsync(mode)

Android
iOS
tvOS
Web
ParameterTypeDescription
modePartial<AudioMode>

Partial audio mode configuration object. Only specified properties will be updated.


Configures the global audio behavior and session settings.

This function allows you to control how your app's audio interacts with other apps, background playback behavior, audio routing, and interruption handling.

Returns:
Promise<void>

A Promise that resolves when the audio mode has been applied.

Example

import { setAudioModeAsync } from 'expo-audio'; // Configure audio for background playback with mixing await setAudioModeAsync({ playsInSilentMode: true, shouldPlayInBackground: true, interruptionMode: 'mixWithOthers' }); // Configure audio for recording await setAudioModeAsync({ allowsRecording: true, playsInSilentMode: true });

Audio.setIsAudioActiveAsync(active)

Android
iOS
tvOS
Web
ParameterTypeDescription
activeboolean

Whether audio should be active (true) or disabled (false).


Enables or disables the audio subsystem globally.

When set to false, this will pause all audio playback and prevent new audio from playing. This is useful for implementing app-wide audio controls or responding to system events.

Returns:
Promise<void>

A Promise that resolves when the audio state has been updated.

Example

import { setIsAudioActiveAsync } from 'expo-audio'; // Disable all audio when app goes to background const handleAppStateChange = async (nextAppState) => { if (nextAppState === 'background') { await setIsAudioActiveAsync(false); } else if (nextAppState === 'active') { await setIsAudioActiveAsync(true); } };

Event Subscriptions

Audio.useAudioSampleListener(player, listener)

Android
iOS
tvOS
Web
ParameterTypeDescription
playerAudioPlayer

The AudioPlayer instance to sample audio from.

listener(data: AudioSample) => void

Function called with each audio sample containing waveform data.


Hook that sets up audio sampling for an AudioPlayer and calls a listener with audio data.

This hook enables audio sampling on the player (if supported) and subscribes to audio sample updates. Audio sampling provides real-time access to audio waveform data for visualization or analysis.

Note: Audio sampling requires RECORD_AUDIO permission on Android and is not supported on all platforms.

Returns:
void

Example

import { useEffect } from 'react'; import { useAudioPlayer, useAudioSampleListener, requestRecordingPermissionsAsync } from 'expo-audio'; function AudioVisualizerComponent() { const player = useAudioPlayer(require('./music.mp3')); // if required on Android, request recording permissions useEffect(() => { async function requestPermission() { const { granted } = await requestRecordingPermissionsAsync(); if (granted) { console.log("Permission granted"); } } requestPermission(); }, []); useAudioSampleListener(player, (sample) => { // Use sample.channels array for audio visualization console.log('Audio sample:', sample.channels[0].frames); }); return <AudioWaveform player={player} />; }

Types

AndroidAudioEncoder

Android

Literal Type: string

Audio encoder options for Android recording.

Specifies the audio codec used to encode recorded audio on Android. Different encoders offer different quality, compression, and compatibility trade-offs.

Acceptable values are: 'default' | 'amr_nb' | 'amr_wb' | 'aac' | 'he_aac' | 'aac_eld'

AndroidOutputFormat

Android

Literal Type: string

Audio output format options for Android recording.

Specifies the container format for recorded audio files on Android. Different formats have different compatibility and compression characteristics.

Acceptable values are: 'default' | '3gp' | 'mpeg4' | 'amrnb' | 'amrwb' | 'aac_adts' | 'mpeg2ts' | 'webm'

AudioEvents

Android
iOS
tvOS
Web

Event types that an AudioPlayer can emit.

These events allow you to listen for changes in playback state and receive real-time audio data. Use player.addListener() to subscribe to these events.

PropertyTypeDescription
audioSampleUpdate(data: AudioSample) => void

Fired when audio sampling is enabled and new sample data is available.

playbackStatusUpdate(status: AudioStatus) => void

Fired when the player's status changes (play/pause/seek/load and so on.).

Deprecated: Use AudioPlayerOptions instead. Options for audio loading behavior.

AudioLoadOptions

Android
iOS
tvOS
Web

Type: AudioPlayerOptions

AudioLockScreenOptions

Android
iOS
tvOS
Web

Options for configuring which playback controls should be displayed on the lock screen.

PropertyTypeDescription
isLiveStream(optional)boolean

Whether the audio is a live stream. When true, the lock screen will hide the duration and scrub bar, and disable seek controls.

showSeekBackward(optional)boolean

Whether the seek backward button should be displayed on the lock screen.

showSeekForward(optional)boolean

Whether the seek forward button should be displayed on the lock screen.

AudioMetadata

Android
iOS
tvOS
Web
PropertyTypeDescription
albumTitle(optional)string
-
artist(optional)string
-
artworkUrl(optional)string
-
title(optional)string
-

AudioMode

Android
iOS
tvOS
Web
PropertyTypeDescription
allowsBackgroundRecording(optional)boolean
Only for:
Android
iOS

Whether audio recording should continue when the app moves to the background.

Default:false
allowsRecording(optional)boolean
Only for:
iOS

Whether the audio session allows recording.

Default:false
interruptionMode(optional)InterruptionMode

Determines how the audio session interacts with other audio sessions.

  • 'doNotMix': Requests exclusive audio focus. Other apps will pause their audio.
  • 'duckOthers': Requests audio focus with ducking. Other apps lower their volume but continue playing.
  • 'mixWithOthers': Audio plays alongside other apps without interrupting them. On Android, this means no audio focus is requested. Best suited for sound effects, UI feedback, or short audio clips.
Default:'mixWithOthers'
interruptionModeAndroid(optional)InterruptionModeAndroid

Deprecated: Use interruptionMode instead, which now works on both platforms.

Android

Determines how the audio session interacts with other sessions on Android.

playsInSilentMode(optional)boolean

Determines if audio playback is allowed when the device is in silent mode. On Android, when false, playback is suppressed when the ringer mode is silent or vibrate.

Default:true
shouldPlayInBackground(optional)boolean

Whether the audio session stays active when the app moves to the background.

Note: On Android, you have to enable the lockscreen controls with setActiveForLockScreen for sustained background playback. Otherwise, the audio will stop after approximately 3 minutes of background playback (OS limitation). Make sure to also appropriately configure the config-plugin.

Default:false
shouldRouteThroughEarpiece(optional)boolean

Whether the audio should route through the earpiece. On iOS, this only has an effect when allowsRecording is true (i.e., the audio session category is .playAndRecord). When false (the default), audio is routed through the speaker.

Default:false

AudioPlayerOptions

Android
iOS
tvOS
Web

Options for configuring audio player behavior.

PropertyTypeDescription
crossOrigin(optional)'anonymous' | 'use-credentials'
Only for:
Web

Determines the cross origin policy used by the underlying native view on web. If undefined (default), does not use CORS at all. If set to 'anonymous', the audio will be loaded with CORS enabled. Note that some audio may not play if CORS is enabled, depending on the CDN settings. If you encounter issues, consider adjusting the crossOrigin property.

Default:undefined
downloadFirst(optional)boolean
Only for:
Android
iOS
Web

If set to true, the system will attempt to download the resource to the device before loading. This value defaults to false.

Works with:

  • Local assets from require('path/to/file')
  • Remote HTTP/HTTPS URLs
  • Asset objects

When enabled, this ensures the audio file is fully downloaded before playback begins. This can improve playback performance and reduce buffering, especially for users managing multiple audio players simultaneously.

On Android and iOS, this will download the audio file to the device's tmp directory before playback begins. The system will purge the file at its discretion.

On web, this will download the audio file to the user's device memory and make it available for the user to play. The system will usually purge the file from memory after a reload or on memory pressure. On web, CORS restrictions apply to the blob url, so you need to make sure the server returns the Access-Control-Allow-Origin header.

keepAudioSessionActive(optional)boolean
Only for:
iOS

If set to true, the audio session will not be deactivated when this player pauses or finishes playback. This prevents interrupting other audio sources (like videos) when the audio ends.

Useful for sound effects that should not interfere with ongoing video playback or other audio. The audio session for this player will not be deactivated automatically when the player finishes playback.

Note: If needed, you can manually deactivate the audio session using setIsAudioActiveAsync(false).

Default:false
preferredForwardBufferDuration(optional)number
Only for:
Android
iOS

The duration in seconds the player should buffer ahead of the current playback position. A higher value improves playback stability at the cost of more memory/network usage.

  • iOS: Maps to AVPlayerItem.preferredForwardBufferDuration. A value of 0 lets the system decide.
  • Android: Configures ExoPlayer's DefaultLoadControl max buffer duration.
  • Web: Not applicable (browser manages buffering).
Default:0 (system default)
updateInterval(optional)number
Only for:
Android
iOS
Web

How often (in milliseconds) to emit playback status updates. Defaults to 500ms.

Default:500ms

Example

import { useAudioPlayer } from 'expo-audio'; export default function App() { const player = useAudioPlayer(source); // High-frequency updates for smooth progress bars const player = useAudioPlayer(source, { updateInterval: 100 }); // Standard updates (default behavior) const player = useAudioPlayer(source, { updateInterval: 500 }); // Low-frequency updates for better performance const player = useAudioPlayer(source, { updateInterval: 1000 }); }

AudioPlaylistEvents

Android
iOS
tvOS
Web

Event types that an AudioPlaylist can emit.

These events allow you to listen for changes in playlist playback state. Use playlist.addListener() to subscribe to these events.

PropertyTypeDescription
playlistStatusUpdate(status: AudioPlaylistStatus) => void

Fired when the playlist's status changes (play/pause/seek/load/track change).

trackChanged(data: { currentIndex: number, previousIndex: number }) => void

Fired when the current track changes (next/previous/skip).

AudioPlaylistLoopMode

Android
iOS
tvOS
Web

Literal Type: string

Loop mode for audio playlist playback.

  • 'none': No looping. Playback stops after the last track.
  • 'single': Loops the current track indefinitely.
  • 'all': Loops the entire playlist, returning to the first track after the last.

Acceptable values are: 'none' | 'single' | 'all'

AudioPlaylistOptions

Android
iOS
tvOS
Web

Options for configuring an audio playlist.

PropertyTypeDescription
crossOrigin(optional)'anonymous' | 'use-credentials'
Only for:
Web

Sets the crossOrigin attribute on the <audio> elements used for playback. Required for CORS-enabled audio files when you need to access audio data.

Default:undefined
loop(optional)AudioPlaylistLoopMode

Loop mode for the playlist.

  • 'none': No looping (default)
  • 'single': Loop the current track
  • 'all': Loop the entire playlist
Default:'none'
sources(optional)AudioSource[]

Initial sources to add to the playlist. Each source can be a local asset, remote URL, or null.

Default:[]
updateInterval(optional)number

How often (in milliseconds) to emit playback status updates. Defaults to 500ms.

Default:500

AudioPlaylistStatus

Android
iOS
tvOS
Web

Status information for an audio playlist.

PropertyTypeDescription
currentIndexnumber

Index of the currently playing track in the playlist.

currentTimenumber

Current playback position in seconds.

didJustFinishboolean

Whether the current track just finished playing.

durationnumber

Total duration of the current track in seconds.

idstring

Unique identifier for the playlist instance.

isBufferingboolean

Whether the player is buffering.

isLoadedboolean

Whether the current track has finished loading.

loopAudioPlaylistLoopMode

Current loop mode.

mutedboolean

Whether the player is muted.

playbackRatenumber

Current playback rate (1.0 = normal speed).

playingboolean

Whether the player is currently playing.

trackCountnumber

Total number of tracks in the playlist.

volumenumber

Current volume level (0.0 to 1.0).

AudioSample

Android
iOS
tvOS
Web

Represents a single audio sample containing waveform data from all audio channels.

Audio samples are provided in real-time when audio sampling is enabled on an AudioPlayer. Each sample contains the raw PCM audio data for all channels (mono has 1 channel, stereo has 2). This data can be used for audio visualization, analysis, or processing.

PropertyTypeDescription
channelsAudioSampleChannel[]

Array of audio channels, each containing PCM frame data. Stereo audio will have 2 channels (left/right).

timestampnumber

Timestamp of this sample relative to the audio track's timeline, in seconds.

AudioSampleChannel

Android
iOS
tvOS
Web

Represents audio data for a single channel (for example, left or right in stereo audio).

Contains the raw PCM (Pulse Code Modulation) audio frames for this channel. Frame values are normalized between -1.0 and 1.0, where 0 represents silence.

PropertyTypeDescription
framesnumber[]

Array of PCM audio frame values, each between -1.0 and 1.0.

AudioSource

Android
iOS
tvOS
Web

Type: string or number or null or object shaped as below:

PropertyTypeDescription
assetId(optional)number

The asset ID of a local audio asset, acquired with the require function. This property is exclusive with the uri property. When both are present, the assetId will be ignored.

headers(optional)Record<string, string>

An object representing the HTTP headers to send along with the request for a remote audio source. On web requires the Access-Control-Allow-Origin header returned by the server to include the current domain.

name(optional)string

An optional display name for the audio source. Useful for showing track names in a queue or playlist UI.

uri(optional)string

A string representing the resource identifier for the audio, which could be an HTTPS address, a local file path, or the name of a static audio file resource.

AudioSourceInfo

Android
iOS
tvOS
Web

Represents audio source information returned from native. This is the object returned when reading sources from a queue.

PropertyTypeDescription
name(optional)string

An optional display name for the audio source.

uri(optional)string

A string representing the resource identifier for the audio.

AudioStatus

Android
iOS
tvOS
Web

Comprehensive status information for an AudioPlayer.

This object contains all the current state information about audio playback, including playback position, duration, loading state, and playback settings. Used by useAudioPlayerStatus() to provide real-time status updates.

PropertyTypeDescription
currentOffsetFromLivenumber | null
Only for:
Android
iOS

Seconds behind the live edge, or null if not a live stream or if the offset cannot be determined.

currentTimenumber

Current playback position in seconds.

didJustFinishboolean

Whether the audio just finished playing.

durationnumber

Total duration of the audio in seconds, or 0 if not yet determined.

errorstring | null

Playback error message, or null if no error. Cleared when a new source is loaded or playback resumes successfully.

idstring

Unique identifier for the player instance.

isBufferingboolean

Whether the player is currently buffering data.

isLiveboolean

Whether the current audio source is a live stream with indefinite duration.

isLoadedboolean

Whether the audio has finished loading and is ready to play.

loopboolean

Whether the audio is set to loop when it reaches the end.

mediaServicesDidReset(optional)boolean
Only for:
iOS

Whether the media services were reset by the system. When true, the player was interrupted because the system's media daemon crashed. The player will automatically attempt to recover by reloading the source and resuming playback.

muteboolean

Whether the player is currently muted.

playbackRatenumber

Current playback rate (1.0 = normal speed).

playbackStatestring

String representation of the player's internal playback state.

playingboolean

Whether the audio is currently playing.

reasonForWaitingToPlaystring

Reason why the player is waiting to play (if applicable).

shouldCorrectPitch(optional)boolean

Whether pitch correction is enabled for rate changes.

Default:true
timeControlStatusstring

String representation of the player's time control status (playing/paused/waiting).

BitRateStrategy

Android
iOS
tvOS
Web

Literal Type: string

Bit rate strategies for audio encoding.

Determines how the encoder manages bit rate during recording, affecting file size consistency and quality characteristics.

Acceptable values are: 'constant' | 'longTermAverage' | 'variableConstrained' | 'variable'

InterruptionMode

Android
iOS
tvOS
Web

Literal Type: string

Audio interruption behavior modes.

Controls how your app's audio interacts with other apps' audio.

  • 'doNotMix': Requests exclusive audio focus. Other apps will pause their audio.

  • 'duckOthers': Requests audio focus with ducking. Other apps lower their volume but continue playing.

  • 'mixWithOthers': Audio plays alongside other apps without interrupting them.

    On Android, this means no audio focus is requested. Best suited for sound effects, UI feedback, or short audio clips. Note that on Android your app won't receive audio focus loss callbacks (for example, during phone calls) when using this mode.

Note: When using setActiveForLockScreen, this must be set to doNotMix.

Default:'mixWithOthers'

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

Deprecated: Use InterruptionMode instead, which now works on both platforms.

InterruptionModeAndroid

Android
iOS
tvOS
Web

Type: InterruptionMode

PermissionExpiration

Android
iOS
tvOS
Web

Literal Type: union

Permission expiration time. Currently, all permissions are granted permanently.

Acceptable values are: 'never' | number

PermissionResponse

Android
iOS
tvOS
Web

An object obtained by permissions get and request functions.

PropertyTypeDescription
canAskAgainboolean

Indicates if user can be asked again for specific permission. If not, one should be directed to the Settings app in order to enable/disable the permission.

expiresPermissionExpiration

Determines time when the permission expires.

grantedboolean

A convenience boolean that indicates if the permission is granted.

statusPermissionStatus

Determines the status of the permission.

PitchCorrectionQuality

iOS

Literal Type: string

Pitch correction quality settings for audio playback rate changes.

When changing playback rate, pitch correction can be applied to maintain the original pitch. Different quality levels offer trade-offs between processing power and audio quality.

Acceptable values are: 'low' | 'medium' | 'high'

PreloadOptions

Android
iOS
tvOS
Web

Options for configuring audio preloading behavior.

PropertyTypeDescription
preferredForwardBufferDuration(optional)number
Only for:
Android
iOS

The duration in seconds the player should buffer ahead of the current playback position. A higher value improves playback stability at the cost of more memory/network usage.

  • iOS: Maps to AVPlayerItem.preferredForwardBufferDuration. A value of 0 lets the system decide.
  • Android: Configures ExoPlayer's buffer duration.
  • Web: Not applicable (browser manages buffering).
Default:10

RecorderState

Android
iOS
tvOS
Web

Current state information for an AudioRecorder.

This object contains detailed information about the recorder's current state, including recording status, duration, and technical details. This is what you get when calling recorder.getStatus() or using useAudioRecorderState().

PropertyTypeDescription
canRecordboolean

Whether the recorder is ready and able to record.

durationMillisnumber

Duration of the current recording in milliseconds.

isRecordingboolean

Whether recording is currently in progress.

mediaServicesDidResetboolean

Whether the media services have been reset (typically indicates a system interruption).

metering(optional)number

Current audio level/volume being recorded (if metering is enabled).

urlstring | null

File URL where the recording will be saved, if available.

RecordingEvents

Android
iOS
tvOS
Web

Event types that an AudioRecorder can emit.

These events are used internally by expo-audio hooks to provide real-time status updates. Use useAudioRecorderState() or the statusListener parameter in useAudioRecorder() instead of subscribing directly.

PropertyTypeDescription
recordingStatusUpdate(status: RecordingStatus) => void

Fired when the recorder's status changes (start/stop/pause/error, and so on).

RecordingInput

Android
iOS
tvOS
Web

Represents an available audio input device for recording.

This type describes audio input sources like built-in microphones, external microphones, or other audio input devices that can be used for recording. Each input has an identifying information that can be used to select the preferred recording source.

PropertyTypeDescription
namestring

Human-readable name of the audio input device.

typestring

Type or category of the input device (for example, 'Built-in Microphone', 'External Microphone').

uidstring

Unique identifier for the input device, used to select the input ('Built-in Microphone', 'External Microphone') for recording.

RecordingOptions

Android
iOS
tvOS
Web
PropertyTypeDescription
androidRecordingOptionsAndroid
Only for:
Android

Recording options for the Android platform.

bitRatenumber

The desired bit rate.

Example

128000

extensionstring

The desired file extension.

Example

.caf

iosRecordingOptionsIos
Only for:
iOS

Recording options for the iOS platform.

isMeteringEnabled(optional)boolean

A boolean that determines whether audio level information will be part of the status object under the "metering" key.

numberOfChannelsnumber

The desired number of channels.

Example

2

sampleRatenumber

The desired sample rate.

Example

44100

webRecordingOptionsWeb
Only for:
Web

Recording options for the Web platform.

RecordingOptionsAndroid

Android

Recording configuration options specific to Android.

Android recording uses MediaRecorder with options for format, encoder, and file constraints. These settings control the output format and quality characteristics.

PropertyTypeDescription
audioEncoderAndroidAudioEncoder

The desired audio encoder. See the AndroidAudioEncoder type for all valid values.

audioSource(optional)RecordingSource

The desired audio Source. See the RecordingSource type for all valid values.

extension(optional)string

The desired file extension.

Example

.caf

maxFileSize(optional)number

The desired maximum file size in bytes, after which the recording will stop (but stopAndUnloadAsync() must still be called after this point).

Example

65536

outputFormatAndroidOutputFormat

The desired file format. See the AndroidOutputFormat type for all valid values.

sampleRate(optional)number

The desired sample rate.

Example

44100

RecordingOptionsIos

iOS

Recording configuration options specific to iOS.

iOS recording uses AVAudioRecorder with extensive format and quality options. These settings provide fine-grained control over the recording characteristics.

PropertyTypeDescription
audioQualityAudioQuality | number

The desired audio quality. See the AudioQuality enum for all valid values.

bitDepthHint(optional)number

The desired bit depth hint.

Example

16

bitRateStrategy(optional)number

The desired bit rate strategy. See the next section for an enumeration of all valid values of bitRateStrategy.

extension(optional)string

The desired file extension.

Example

.caf

linearPCMBitDepth(optional)number

The desired PCM bit depth.

Example

16

linearPCMIsBigEndian(optional)boolean

A boolean describing if the PCM data should be formatted in big endian.

linearPCMIsFloat(optional)boolean

A boolean describing if the PCM data should be encoded in floating point or integral values.

outputFormat(optional)string | IOSOutputFormat | number

The desired file format. See the IOSOutputFormat enum for all valid values.

sampleRate(optional)number

The desired sample rate.

Example

44100

RecordingOptionsWeb

Web

Recording options for the web.

Web recording uses the MediaRecorder API, which has different capabilities compared to native platforms. These options map directly to MediaRecorder settings.

PropertyTypeDescription
bitsPerSecond(optional)number

Target bits per second for the recording.

mimeType(optional)string

MIME type for the recording (for example, 'audio/webm', 'audio/mp4').

RecordingSource

Android

Literal Type: string

Recording source for android.

An audio source defines both a default physical source of audio signal, and a recording configuration.

  • camcorder: Microphone audio source tuned for video recording, with the same orientation as the camera if available.
  • default: The default audio source.
  • mic: Microphone audio source.
  • unprocessed: Microphone audio source tuned for unprocessed (raw) sound if available, behaves like default otherwise.
  • voice_communication: Microphone audio source tuned for voice communications such as VoIP. It will for instance take advantage of echo cancellation or automatic gain control if available.
  • voice_performance: Source for capturing audio meant to be processed in real time and played back for live performance (e.g karaoke). The capture path will minimize latency and coupling with playback path.
  • voice_recognition: Microphone audio source tuned for voice recognition.

Acceptable values are: 'camcorder' | 'default' | 'mic' | 'remote_submix' | 'unprocessed' | 'voice_communication' | 'voice_performance' | 'voice_recognition'

RecordingStartOptions

Android
iOS
tvOS
Web

Options for controlling how audio recording is started.

PropertyTypeDescription
atTime(optional)number
Only for:
iOS

The time in seconds to wait before starting the recording. If not provided, recording starts immediately.

Platform behavior:

  • Android: Ignored, recording starts immediately
  • iOS: Uses native AVAudioRecorder.record(atTime:) for precise timing.
  • Web: Ignored, recording starts immediately
On iOS, the recording process starts immediately (you'll see status updates), but actual audio capture begins after the specified delay. This is not a countdown, since the recorder is active but silent during the delay period.
forDuration(optional)number
Only for:
Android
iOS
Web

The duration in seconds after which recording should automatically stop. If not provided, recording continues until manually stopped.

RecordingStatus

Android
iOS
tvOS
Web

Status information for recording operations from the event system.

This type represents the status data emitted by recordingStatusUpdate events. It contains high-level information about the recording session and any errors. Used internally by the event system. Most users should use useAudioRecorderState() instead.

PropertyTypeDescription
errorstring | null

Error message if an error occurred, null otherwise.

hasErrorboolean

Whether an error occurred during recording.

idstring

Unique identifier for the recording session.

isFinishedboolean

Whether the recording has finished (stopped).

mediaServicesDidReset(optional)boolean
Only for:
iOS

Whether the media services were reset by the system. When true, the recording was interrupted because the system's media daemon crashed. The recorder is now invalid and must be re-prepared by calling prepareToRecordAsync().

urlstring | null

File URL of the completed recording, if available.

Enums

AudioQuality

Android
iOS
tvOS
Web

Audio quality levels for recording.

Predefined quality levels that balance file size and audio fidelity. Higher quality levels produce better sound but larger files and require more processing power.

MIN

AudioQuality.MIN = 0

Minimum quality: smallest file size, lowest fidelity.

LOW

AudioQuality.LOW = 32

Low quality: good for voice recordings where file size matters.

MEDIUM

AudioQuality.MEDIUM = 64

Medium quality: balanced option for most use cases.

HIGH

AudioQuality.HIGH = 96

High quality: good fidelity, larger file size.

MAX

AudioQuality.MAX = 127

Maximum quality: best fidelity, largest file size.

IOSOutputFormat

iOS

Audio output format options for iOS recording.

Comprehensive enum of audio formats supported by iOS for recording. Each format has different characteristics in terms of quality, file size, and compatibility. Some formats like LINEARPCM offer the highest quality but larger file sizes, while compressed formats like AAC provide good quality with smaller files.

MPEGLAYER1

IOSOutputFormat.MPEGLAYER1 = ".mp1"

MPEGLAYER2

IOSOutputFormat.MPEGLAYER2 = ".mp2"

MPEGLAYER3

IOSOutputFormat.MPEGLAYER3 = ".mp3"

MPEG4AAC

IOSOutputFormat.MPEG4AAC = "aac "

MPEG4AAC_ELD

IOSOutputFormat.MPEG4AAC_ELD = "aace"

MPEG4AAC_ELD_SBR

IOSOutputFormat.MPEG4AAC_ELD_SBR = "aacf"

MPEG4AAC_ELD_V2

IOSOutputFormat.MPEG4AAC_ELD_V2 = "aacg"

MPEG4AAC_HE

IOSOutputFormat.MPEG4AAC_HE = "aach"

MPEG4AAC_LD

IOSOutputFormat.MPEG4AAC_LD = "aacl"

MPEG4AAC_HE_V2

IOSOutputFormat.MPEG4AAC_HE_V2 = "aacp"

MPEG4AAC_SPATIAL

IOSOutputFormat.MPEG4AAC_SPATIAL = "aacs"

AC3

IOSOutputFormat.AC3 = "ac-3"

AES3

IOSOutputFormat.AES3 = "aes3"

APPLELOSSLESS

IOSOutputFormat.APPLELOSSLESS = "alac"

ALAW

IOSOutputFormat.ALAW = "alaw"

AUDIBLE

IOSOutputFormat.AUDIBLE = "AUDB"

60958AC3

IOSOutputFormat.60958AC3 = "cac3"

MPEG4CELP

IOSOutputFormat.MPEG4CELP = "celp"

ENHANCEDAC3

IOSOutputFormat.ENHANCEDAC3 = "ec-3"

MPEG4HVXC

IOSOutputFormat.MPEG4HVXC = "hvxc"

ILBC

IOSOutputFormat.ILBC = "ilbc"

APPLEIMA4

IOSOutputFormat.APPLEIMA4 = "ima4"

LINEARPCM

IOSOutputFormat.LINEARPCM = "lpcm"

MACE3

IOSOutputFormat.MACE3 = "MAC3"

MACE6

IOSOutputFormat.MACE6 = "MAC6"

AMR

IOSOutputFormat.AMR = "samr"

AMR_WB

IOSOutputFormat.AMR_WB = "sawb"

DVIINTELIMA

IOSOutputFormat.DVIINTELIMA = 1836253201

MICROSOFTGSM

IOSOutputFormat.MICROSOFTGSM = 1836253233

QUALCOMM

IOSOutputFormat.QUALCOMM = "Qclp"

QDESIGN2

IOSOutputFormat.QDESIGN2 = "QDM2"

QDESIGN

IOSOutputFormat.QDESIGN = "QDMC"

MPEG4TWINVQ

IOSOutputFormat.MPEG4TWINVQ = "twvq"

ULAW

IOSOutputFormat.ULAW = "ulaw"

PermissionStatus

Android
iOS
tvOS
Web

DENIED

PermissionStatus.DENIED = "denied"

User has denied the permission.

GRANTED

PermissionStatus.GRANTED = "granted"

User has granted the permission.

UNDETERMINED

PermissionStatus.UNDETERMINED = "undetermined"

User hasn't granted or denied the permission yet.