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 Player 时支持的格式。iOS 音频和视频格式文档 列出了 Apple 设备支持的媒体格式。
🌐 The Android media format support documentation covers formats supported when using Expo Player on Android. The iOS audio and video format documentation lists supported media formats for Apple devices.
请注意,如果耳机或蓝牙音频设备断开连接,音频会自动停止。
🌐 Note that audio automatically stops if headphones/Bluetooth audio devices are disconnected.
安装
🌐 Installation
If you are installing this in an existing React Native app, make sure to install expo in your project.
应用配置中的配置
🌐 Configuration in app config
如果你在项目中使用配置插件(连续原生生成 (CNG)),可以使用其内置的 config 插件 配置 expo-audio。该插件允许你配置在运行时无法设置、需要构建新的应用二进制文件才能生效的各种属性。如果你的应用未使用 CNG,则需要手动配置该库。
🌐 You can configure expo-audio using its built-in config plugin if you use config plugins in your project (Continuous Native Generation (CNG)). The plugin allows you to configure various properties that cannot be set at runtime and require building a new app binary to take effect. If your app does not use CNG, then you'll need to manually configure the library.
Example app.json with config plugin
Configurable properties
用法
🌐 Usage
播放声音
🌐 Playing sounds
录制声音
🌐 Recording sounds
在 Android 和 iOS 上,expo-audio 默认将录音保存在应用的缓存目录中。当设备存储空间不足时,系统可能会删除缓存文件。要将新录音保存到更持久的位置,请将 { ...RecordingPresets.HIGH_QUALITY, directory: 'document' } 传递给 useAudioRecorder 或 prepareToRecordAsync()。这会将它们存储在应用的文档目录下。对于已经保存在缓存中的现有录音,请使用返回的录音 URI 并通过 expo-file-system 移动它们。
🌐 On Android and iOS, expo-audio saves recordings in the app's cache directory by default. The system may delete cache files when the device runs low on storage. To keep new recordings in a more persistent location, pass { ...RecordingPresets.HIGH_QUALITY, directory: 'document' } to useAudioRecorder or prepareToRecordAsync(). This stores them under the app's document directory. For existing recordings already saved in cache, use the returned recording URI to move them with expo-file-system.
在后台播放音频
🌐 Playing audio in the background
后台音频播放允许你的应用在移到后台或设备屏幕锁定时继续播放音频。
🌐 Background audio playback allows your app to continue playing audio when it moves to the background or when the device screen locks.
配置
🌐 Configuration
要启用后台音频播放,请在你的 应用配置 中使用 config 插件:
🌐 To enable background audio playback, use the config plugin in your app config:
上述配置会自动配置所需的本地设置:
🌐 The above configuration automatically configures the required native settings:
- Android添加了
FOREGROUND_SERVICE和FOREGROUND_SERVICE_MEDIA_PLAYBACK权限。同时在应用的 AndroidManifest.xml 中声明了一个媒体播放前台服务 (AudioControlsService)。 - iOS添加了
audioUIBackgroundMode功能
用法
🌐 Usage
在使用配置插件配置你的应用后,你需要:
🌐 After configuring your app with the config plugin, you need to:
- 配置音频会话以允许后台播放
- 启用锁屏控制(在 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(() => { // Configure audio session for background playback setAudioModeAsync({ playsInSilentMode: true, shouldPlayInBackground: true, interruptionMode: 'doNotMix', }); }, []); const handlePlay = () => { // Enable lock screen controls with metadata player.setActiveForLockScreen(true, { title: 'My Audio Title', artist: 'Artist Name', albumTitle: 'Album Name', artworkUrl: 'https://example.com/artwork.jpg', // optional }); // Start playback - this will continue in the background player.play(); }; const handleStop = () => { player.pause(); // Optionally disable lock screen controls when done player.setActiveForLockScreen(false); }; return ( <View> <Button title="玩" onPress={handlePlay} /> <Button title="停止" onPress={handleStop} /> </View> ); }
注意:在 Android 上,你必须使用
setActiveForLockScreen启用锁屏控制以实现持续的后台播放。否则,音频将在大约 3 分钟的后台播放后停止(操作系统限制)。请确保适当 配置配置插件。
- 媒体通知出现在通知栏中,并带有播放控制
- 音频会在后台无限播放
- 用户可以从锁屏和通知栏控制播放
- 前台服务在播放过程中保持播放活动
在 iOS 上,一旦用 shouldPlayInBackground: true 配置了音频会话,音频播放将在后台无缝继续。锁屏控制是可选的,但通过在锁屏和控制中心提供播放控制,可以增强用户体验。
🌐 On iOS, audio playback continues seamlessly in the background once the audio session is configured with shouldPlayInBackground: true. Lock screen controls are optional but enhance the user experience by providing playback controls on the lock screen and Control Center.
Are you using this library in an existing React Native app?
如果你没有使用连续原生生成(CNG)(你是手动使用原生 android 和 ios 项目),那么你需要为后台播放配置以下内容:
🌐 If you're not using Continuous Native Generation (CNG) (you're using native android and ios projects manually), then you need to configure the following for background playback:
-
对于 Android,请添加到 android/app/src/main/AndroidManifest.xml:
android/app/src/main/AndroidManifest.xml -
对于 iOS,添加到 ios/YourApp/Info.plist :
ios/YourApp/Info.plist
在后台录制音频
🌐 Recording audio in the background
警告 后台录音会显著影响电池寿命。仅在应用功能需要时启用。
后台音频录制允许你的应用在切换到后台或设备屏幕锁定时继续录制。
🌐 Background audio recording allows your app to continue recording when it moves to the background or when the device screen locks.
要启用后台录音,请在你的 应用配置 中使用配置插件:
🌐 To enable background recording, use the config plugin in your app config:
上述配置会自动配置所需的本地设置:
🌐 The above configuration automatically configures the required native settings:
- Android添加了
FOREGROUND_SERVICE、FOREGROUND_SERVICE_MICROPHONE和POST_NOTIFICATIONS权限。同时在应用的 AndroidManifest.xml 中声明了一个音频录制前台服务。 - iOS添加了
audioUIBackgroundMode功能
Are you using this library in an existing React Native app?
如果你没有使用连续本地生成(CNG)(你是在手动使用原生 android 和 ios 项目),那么你需要在你的原生项目中配置以下权限:
🌐 If you're not using Continuous Native Generation (CNG) (you're using native android and ios projects manually), then you need to configure the following permissions in your native projects:
-
对于 Android,请添加到 android/app/src/main/AndroidManifest.xml:
android/app/src/main/AndroidManifest.xml -
对于 iOS,添加到 ios/YourApp/Info.plist :
ios/YourApp/Info.plist
用法
🌐 Usage
在配置好应用后,使用 setAudioModeAsync 在运行时启用后台录制:
🌐 After configuring your app, enable background recording at runtime using 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(); // Recording continues in background
在 Android 上,后台录音需要前台服务,它会显示一个带有“正在录音”文字和停止按钮的持续通知。在录音进行时,该通知无法被关闭,录音停止时通知会自动消失。
🌐 On Android, background recording requires a foreground service, which displays a persistent notification with the text "Recording audio" and a stop button. This notification cannot be dismissed while recording is active and automatically disappears when recording stops.
后台录音不需要通知权限。如果用户没有授予权限,录音仍然可以正常进行,而且通知只会出现在任务管理器里,而不会出现在通知栏。
🌐 Background recording does not require the notification permission. If the user has not granted it, recording still works and the notification appears only in the Task Manager instead of the notification drawer.
在 iOS 上,当应用处于后台或屏幕锁定时,后台录音会无缝继续。除了系统状态栏之外,不会向应用用户显示额外的通知或指示。
🌐 On iOS, background recording continues seamlessly when the app is in the background or the screen locks. No additional notifications or indicators are shown to the app user beyond the system status bar.
直接使用 AudioPlayer
🌐 Using the AudioPlayer directly
在大多数情况下,使用 useAudioPlayer 钩子来创建 AudioPlayer 实例。它管理播放器的生命周期,并确保在组件卸载时正确释放。然而,在一些高级用例中,你可能需要创建一个 AudioPlayer,使其在组件生命周期之外仍然存在。
在这些情况下,使用 createAudioPlayer 函数。你需要意识到这种方法所带来的风险,因为在播放器不再需要时,调用 release() 方法的责任在于你。如果处理不当,这种方法可能导致内存泄漏。
🌐 In most cases, use the useAudioPlayer hook to create an AudioPlayer instance. It manages the player's lifecycle and ensures proper disposal when the component unmounts. However, in some advanced use cases, you may need to create an AudioPlayer that persists beyond the component's lifecycle.
In those cases, use the createAudioPlayer function. You need to be aware of the risks that come with this approach, as it is your responsibility to call the release() method when the player is no longer needed. If not handled properly, this approach may lead to memory leaks.
import { createAudioPlayer } from 'expo-audio'; const player = createAudioPlayer(audioSource);
网络使用注意事项
🌐 Notes on web usage
- Chrome上的MediaRecorder问题会生成缺少持续时间元数据的WebM文件。查看未解决的Chromium问题。
- 不同浏览器中的 MediaRecorder 编码选项和其他配置不一致。在你的应用中使用像 kbumsik/opus-media-recorder 或 ai/audio-recorder-polyfill 这样的 polyfill 可以改善体验。传递给
prepareToRecordAsync的任何选项都会直接传递给 MediaRecorder API,并且同样适用于 polyfill。 - 网络浏览器要求网站必须通过安全方式提供服务,才能使用麦克风。更多详情请参见 MediaDevices
getUserMedia()安全性。
应用接口
🌐 API
import { useAudioPlayer, useAudioRecorder } from 'expo-audio';
No API data file found, sorry!