This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
Expo 音频 (expo-audio)
一个提供 API 用于在应用中实现音频播放和录音的库。
expo-audio 是一个跨平台音频库,用于访问设备的原生音频能力。
Android 媒体格式支持文档 说明了在 Android 上使用 Expo 播放器时支持的格式。iOS 音频和视频格式文档 列出了 Apple 设备支持的媒体格式。
请注意,如果耳机/蓝牙音频设备断开连接,音频会自动停止。
安装
If you are installing this in an existing React Native app, make sure to install expo in your project.
app 配置中的配置
如果你在项目中使用配置插件(Continuous Native Generation(CNG)),可以使用 expo-audio 内置的 config plugin 进行配置。该插件允许你配置一些无法在运行时设置的属性,这些属性需要构建新的应用二进制文件后才会生效。如果你的应用不使用 CNG,那么你需要手动配置该库。
Example app.json with config plugin
Configurable properties
用法
播放声音
录制声音
在 Android 和 iOS 上,expo-audio 默认会将录音保存到应用的缓存目录。系统在设备存储空间不足时可能会删除缓存文件。若要将新录音保存在更持久的位置,请将 { ...RecordingPresets.HIGH_QUALITY, directory: 'document' } 传给 useAudioRecorder 或 prepareToRecordAsync()。这会将它们存储在应用的文档目录下。对于已经保存在缓存中的现有录音,请使用返回的录音 URI,并结合 expo-file-system 将其移动。
在后台播放音频
后台音频播放允许你的应用在进入后台或设备屏幕锁定时继续播放音频。
配置
要启用后台音频播放,请在你的 app config 中使用 config plugin:
上述配置会自动设置所需的原生配置:
- Android添加
FOREGROUND_SERVICE和FOREGROUND_SERVICE_MEDIA_PLAYBACK权限。还会在应用的 AndroidManifest.xml 中声明一个媒体播放前台服务 (AudioControlsService)。 - iOS添加
audioUIBackgroundMode能力
用法
使用 config plugin 配置应用后,你需要:
- 配置音频会话以允许后台播放
- 启用锁屏控制(在 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 上,你必须使用
setActiveForLockScreen启用锁屏控制,才能持续后台播放。否则,音频将在大约 3 分钟的后台播放后停止(这是系统限制)。请确保正确配置 config plugin。
- 通知栏中会显示带有播放控制的媒体通知
- 音频会在后台无限期播放
- 用户可以从锁屏和通知中控制播放
- 前台服务会在播放期间保持播放持续运行
在 iOS 上,一旦音频会话配置为 shouldPlayInBackground: true,音频播放就会在后台无缝继续。锁屏控制是可选的,但它们可以通过在锁屏和控制中心提供播放控制来提升用户体验。
Are you using this library in an existing React Native app?
如果你没有使用 Continuous Native Generation (CNG)(也就是你在手动使用原生 android 和 ios 项目),那么你需要为后台播放配置以下内容:
-
对于 Android,请添加到 android/app/src/main/AndroidManifest.xml:
android/app/src/main/AndroidManifest.xml -
对于 iOS,请添加到 ios/YourApp/Info.plist:
ios/YourApp/Info.plist
在后台录制音频
后台录制会显著影响电池续航。仅在你的应用功能确实需要时才启用它。
后台音频录制允许你的应用在进入后台或设备屏幕锁定时继续录制。
要启用后台录制,请在你的 app config 中使用 config plugin:
上述配置会自动设置所需的原生配置:
- Android添加
FOREGROUND_SERVICE、FOREGROUND_SERVICE_MICROPHONE和POST_NOTIFICATIONS权限。还会在应用的 AndroidManifest.xml 中声明一个音频 录制前台服务。 - iOS添加
audioUIBackgroundMode能力
Are you using this library in an existing React Native app?
如果你没有使用 Continuous Native Generation (CNG)(也就是你在手动使用原生 android 和 ios 项目),那么你需要在原生项目中配置以下权限:
-
对于 Android,请添加到 android/app/src/main/AndroidManifest.xml:
android/app/src/main/AndroidManifest.xml -
对于 iOS,请添加到 ios/YourApp/Info.plist:
ios/YourApp/Info.plist
用法
配置应用后,使用 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 上,后台录制需要一个前台服务,它会显示一条带有“正在录制音频”文本和停止按钮的持久通知。在录制处于活动状态时,这条通知无法被清除,并且会在录制停止时自动消失。
在 iOS 上,当应用处于后台或屏幕锁定时,后台录制会无缝继续。除了系统状态栏之外,不会向应用用户显示任何额外的通知或指示。
直接使用 AudioPlayer
在大多数情况下,使用 useAudioPlayer hook 来创建 AudioPlayer 实例。它会管理播放器的生命周期,并确保组件卸载时正确释放。不过,在某些高级用例中,你可能需要创建一个会持续存在于组件生命周期之外的 AudioPlayer。
在这些情况下,请使用 createAudioPlayer 函数。你需要注意这种方式带来的风险,因为当播放器不再需要时,调用 release() 方法是你的责任。如果处理不当,这种方式可能会导致内存泄漏。
import { createAudioPlayer } from 'expo-audio'; const player = createAudioPlayer(audioSource);
Web 使用说明
- Chrome 上的一个 MediaRecorder 问题会生成缺少时长元数据的 WebM 文件。查看未解决的 Chromium 问题。
- MediaRecorder 的编码选项和其他配置在不同浏览器之间并不一致。在你的应用中使用 kbumsik/opus-media-recorder 或 ai/audio-recorder-polyfill 这样的 polyfill 会改善你的体验。传递给
prepareToRecordAsync的任何选项都会直接传递给 MediaRecorder API,因此也会传递给该 polyfill。 - Web 浏览器要求网站通过安全方式提供服务,才能访问麦克风。更多详情请参阅 MediaDevices
getUserMedia()security。
API
import { useAudioPlayer, useAudioRecorder } from 'expo-audio';
Constants
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
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.
AudioPlayerAn 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()} /> ); }
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.
AudioStatusThe 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> ); }
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.
AudioPlaylistAn 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> ); }
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.
AudioPlaylistStatusThe 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> ); }
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.
AudioRecorderAn 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} /> ); }
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.
RecorderStateThe 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> ); }
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_AUDIOpermission on Android and is not supported on all platforms.
voidExample
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} />; }
Hook that creates a native audio stream for real-time PCM microphone capture.
Call stream.start() to begin and stream.stop() to end.
Requires microphone permission via requestRecordingPermissionsAsync().
AudioStreamResultClasses
Type: Class extends SharedObject<AudioEvents>
AudioPlayer Properties
booleanBoolean value indicating whether audio sampling is supported on the platform.
booleanBoolean value indicating whether the player is finished loading.
booleanBoolean value indicating whether the player is currently paused.
numberThe current playback rate of the audio. It accepts different values depending on the platform:
- Android:
0.1to2.0 - iOS:
0.0to2.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; }
booleanBoolean value indicating whether the player is currently playing.
booleanA boolean describing if we are correcting the pitch for a changed rate.
numberThe 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
Removes this player from lock screen controls if it's currently active. This will clear the lock screen's now playing info.
voidSets 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,
interruptionModemust be set todoNotMixusingsetAudioModeAsync. Without this, the OS might not associate lock screen controls with your player.
voidSets the current playback rate of the audio.
voidType: Class extends SharedObject<AudioPlaylistEvents>
AudioPlaylist Properties
numberIndex of the currently playing track in the playlist.
booleanBoolean value indicating whether the playlist is buffering.
booleanBoolean value indicating whether the current track has finished loading.
booleanBoolean value indicating whether the playlist is currently muted.
booleanBoolean value indicating whether the playlist is currently playing.
AudioSourceInfo[]The audio sources currently in the playlist.
AudioPlaylist Methods
Insert a track at a specific position in the playlist.
voidSkip 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.
voidSkip 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.
voidType: Class extends SharedObject<RecordingEvents>
AudioRecorder Properties
booleanBoolean value indicating whether the recording is in progress.
AudioRecorder Methods
Returns a list of available recording inputs. This method can only be called if the Recording has been prepared.
RecordingInput[]A Promise that is fulfilled with an array of RecordingInput objects.
Returns the currently-selected recording input. This method can only be called if the Recording has been prepared.
Promise<RecordingInput>A Promise that is fulfilled with a RecordingInput object.
Status of the current recording.
RecorderStateDeprecated: Use
record({ forDuration: seconds })instead.
Stops the recording once the specified time has elapsed.
voidSets the current recording input.
voidA Promise that is resolved if successful or rejected if not.
Deprecated: Use
record({ atTime: seconds })instead.
Starts the recording at the given time.
voidStop the recording.
Promise<void>Type: Class extends SharedObject<AudioStreamEvents>
A native audio stream that captures PCM audio from the microphone in real-time.
AudioStream Properties
numberActual number of channels being delivered. Available after start().
AudioStream Methods
Begins capturing audio from the microphone.
Requires microphone permission — call requestRecordingPermissionsAsync() first.
Promise<void>Methods
Releases all preloaded audio sources to free memory.
Promise<void>Creates an instance of an AudioPlayer that doesn't release automatically.
For most use cases you should use the
useAudioPlayerhook instead. See the Using theAudioPlayerdirectly section for more details.
AudioPlayerCreates an instance of an AudioPlaylist that doesn't release automatically.
For most use cases you should use the
useAudioPlaylisthook instead.
AudioPlaylistReturns 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().
Promise<string[]>An array of URI strings for sources currently in the preload cache.
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().
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 };
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.
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()} />; }
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.
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); } };
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.
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); } };
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.
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 });
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.
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
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_AUDIOpermission on Android and is not supported on all platforms.
voidExample
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
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'
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'
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.
Deprecated: Use
AudioPlayerOptionsinstead. Options for audio loading behavior.
Type: AudioPlayerOptions
Options for configuring which playback controls should be displayed on the lock screen.
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.
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'
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.
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.
Represents audio source information returned from native. This is the object returned when reading sources from a queue.
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.
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'
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 todoNotMix.
Default:'mixWithOthers'
Acceptable values are: 'mixWithOthers' | 'doNotMix' | 'duckOthers'
Deprecated: Use
InterruptionModeinstead, which now works on both platforms.
Type: InterruptionMode
Literal type: union
Permission expiration time. Currently, all permissions are granted permanently.
Acceptable values are: 'never' | number
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'
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().
Literal type: string
Directory where the recording file is stored.
cache: Stores recordings in the app cache directory, a place to store files that can be deleted by the system when the device runs low on storage.document: Stores recordings in the app document directory, a place to store files that are safe from being deleted by the system.
Acceptable values are: 'cache' | 'document'
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.
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.
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.
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.
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.
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 likedefaultotherwise.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'
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.
Enums
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.
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.