Expo AV
一个为音频和视频播放提供独立 API 的通用库。
For the complete documentation index, see llms.txt. Use this Use this file to discover all available pages.
已弃用:expo-av中的Video和AudioAPI 现已弃用,并已由改进版的expo-video和expo-audio替代。我们建议改用这些库。expo-av不再接收补丁更新,并将在 SDK 55 中移除。
Audio.Sound 对象和 Video 组件共享一个用于媒体播放的统一命令式 API。
请注意,对于 Video,所有操作也可以通过组件上的 props 使用。不过,对于大多数需要更精细控制视频播放状态的应用,我们建议使用这种命令式播放 API。
有关 Audio.Sound 和 Video 的播放 API 示例,请参阅 播放列表示例应用。
tvOS(Apple TV)不支持音频录制 API。
安装
- npx expo install expo-avIf you are installing this in an existing React Native app, make sure to install expo in your project.
在 app 配置中进行配置
如果你在项目中使用 config plugins(Continuous Native Generation (CNG)),可以使用 expo-av 内置的 config plugin 进行配置。该插件允许你配置各种无法在运行时设置的属性,并且这些属性需要构建新的应用二进制文件后才会生效。如果你的应用不使用 CNG,那么你需要手动配置该库。
Example app.json with config plugin
{ "expo": { "plugins": [ [ "expo-av", { "microphonePermission": "允许 $(PRODUCT_NAME) 访问你的麦克风。" } ] ] } }
Configurable properties
| Name | Default | Description |
|---|---|---|
microphonePermission | "允许 $(PRODUCT_NAME) 访问你的麦克风" | Only for: iOS 用于设置 |
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.permission.RECORD_AUDIO权限:<uses-permission android:name="android.permission.RECORD_AUDIO" /> -
对于 iOS,请在项目的 ios/[app]/Info.plist 中添加
NSMicrophoneUsageDescription:<key>NSMicrophoneUsageDescription</key> <string>允许 $(PRODUCT_NAME) 访问你的麦克风</string>
使用
在本页中,我们引用了对 playbackObject 的操作。下面是获取音频和视频引用的示例:
示例:Audio.Sound
await Audio.setAudioModeAsync({ playsInSilentModeIOS: true }); const playbackObject = new Audio.Sound(); // 或者 const { sound: playbackObject } = await Audio.Sound.createAsync( { uri: 'http://foo/bar.mp3' }, { shouldPlay: true } );
有关 Audio.Sound.createAsync() 的更多信息,请参阅 音频文档。
示例:Video
%%placeholder-start%%... %%placeholder-end%% _handleVideoRef = component => { const playbackObject = component; ... } %%placeholder-start%%... %%placeholder-end%% render() { return ( <Video ref={this._handleVideoRef} /> %%placeholder-start%%... %%placeholder-end%% ) }
有关更多信息,请参阅 视频文档。
示例:setOnPlaybackStatusUpdate()
_onPlaybackStatusUpdate = playbackStatus => { if (!playbackStatus.isLoaded) { // 为未加载状态更新你的 UI if (playbackStatus.error) { console.log(`播放过程中遇到致命错误:${playbackStatus.error}`); // 在 Slack 或论坛上将错误发送给 Expo 团队,以便我们帮助你调试! } } else { // 为已加载状态更新你的 UI if (playbackStatus.isPlaying) { // 为播放状态更新你的 UI } else { // 为暂停状态更新你的 UI } if (playbackStatus.isBuffering) { // 为缓冲状态更新你的 UI } if (playbackStatus.didJustFinish && !playbackStatus.isLooping) { // 播放器刚刚播放完成并将停止。也许你想播放别的内容? } %%placeholder-start%%... %%placeholder-end%% } }; // 加载 playbackObject 并获取引用。 playbackObject.setOnPlaybackStatusUpdate(this._onPlaybackStatusUpdate);
示例:将媒体精确循环 20 次
const N = 20; %%placeholder-start%%... %%placeholder-end%% _onPlaybackStatusUpdate = playbackStatus => { if (playbackStatus.didJustFinish) { if (this.state.numberOfLoops == N - 1) { playbackObject.setIsLooping(false); } this.setState({ numberOfLoops: this.state.numberOfLoops + 1 }); } }; %%placeholder-start%%... %%placeholder-end%% this.setState({ numberOfLoops: 0 }); // 加载 playbackObject 并获取引用。 playbackObject.setOnPlaybackStatusUpdate(this._onPlaybackStatusUpdate); playbackObject.setIsLooping(true);
什么是 seek 容差,以及我为什么要使用它 iOS
当请求跳转到一个 A/V 项目时,iOS 中的原生播放器有时可能会跳到一个略有不同的时间点。Apple 文档中提到的这种技术,见 Apple 文档,用于缩短 seekTo 调用所需的时间(播放器可能会决定从与请求不同的时间点立即播放,而不是解码请求的精确部分并带着解码延迟进行播放)。
如果精度很重要,你可以指定播放器进行跳转时允许的容差。不过,这会导致延迟增加。
API
import { Audio, Video } from 'expo-av';
Constants
Type: AVPlaybackStatusToSet
The default initial AVPlaybackStatusToSet of all Audio.Sound objects and Video components is as follows:
{ progressUpdateIntervalMillis: 500, positionMillis: 0, shouldPlay: false, rate: 1.0, shouldCorrectPitch: false, volume: 1.0, isMuted: false, isLooping: false, }
This default initial status can be overwritten by setting the optional initialStatus in loadAsync() or Audio.Sound.createAsync().
Interfaces
Gets the AVPlaybackStatus of the playbackObject.
Promise<AVPlaybackStatus>A Promise that is fulfilled with the AVPlaybackStatus of the playbackObject.
| Parameter | Type | Description |
|---|---|---|
| status | AVPlaybackStatusToSet | The new |
Sets a new AVPlaybackStatusToSet on the playbackObject. This method can only be called if the media has been loaded.
Promise<AVPlaybackStatus>A Promise that is fulfilled with the AVPlaybackStatus of the playbackObject once the new status has been set successfully,
or rejects if setting the new status failed. See below for details on AVPlaybackStatus.
Extends: AV
On the playbackObject reference, the following API is provided.
| Parameter | Type | Description |
|---|---|---|
| source | AVPlaybackSource | The source of the media. |
| initialStatus(optional) | AVPlaybackStatusToSet | The initial intended |
| downloadAsync(optional) | boolean | If set to |
Loads the media from source into memory and prepares it for playing. This must be called before calling setStatusAsync()
or any of the convenience set status methods. This method can only be called if the playbackObject is in an unloaded state.
Promise<AVPlaybackStatus>A Promise that is fulfilled with the AVPlaybackStatus of the playbackObject once it is loaded, or rejects if loading failed.
The Promise will also reject if the playbackObject was already loaded. See below for details on AVPlaybackStatus.
This is equivalent to playbackObject.setStatusAsync({ shouldPlay: false }).
Promise<AVPlaybackStatus>This is equivalent to playbackObject.setStatusAsync({ shouldPlay: true }).
Playback may not start immediately after calling this function for reasons such as buffering. Make sure to update your UI based
on the isPlaying and isBuffering properties of the AVPlaybackStatus.
Promise<AVPlaybackStatus>| Parameter | Type | Description |
|---|---|---|
| positionMillis | number | The desired position of playback in milliseconds. |
| tolerances(optional) | AVPlaybackTolerance | The tolerances are used only on iOS (more details). |
This is equivalent to playbackObject.setStatusAsync({ shouldPlay: true, positionMillis, seekMillisToleranceAfter: tolerances.seekMillisToleranceAfter, seekMillisToleranceBefore: tolerances.seekMillisToleranceBefore }).
Playback may not start immediately after calling this function for reasons such as buffering. Make sure to update your UI based
on the isPlaying and isBuffering properties of the AVPlaybackStatus.
Promise<AVPlaybackStatus>| Parameter | Type | Description |
|---|---|---|
| status | AVPlaybackStatusToSet | The new |
Replays the playback item. When using playFromPositionAsync(0) the item is seeked to the position at 0 ms.
On iOS this method uses internal implementation of the player and is able to play the item from the beginning immediately.
Promise<AVPlaybackStatus>A Promise that is fulfilled with the AVPlaybackStatus of the playbackObject once the new status has been set successfully,
or rejects if setting the new status failed.
| Parameter | Type | Description |
|---|---|---|
| isLooping | boolean | A boolean describing if the media should play once ( |
This is equivalent to playbackObject.setStatusAsync({ isLooping }).
Promise<AVPlaybackStatus>| Parameter | Type | Description |
|---|---|---|
| isMuted | boolean | A boolean describing if the audio of this media should be muted. |
This is equivalent to playbackObject.setStatusAsync({ isMuted }).
Promise<AVPlaybackStatus>| Parameter | Type | Description |
|---|---|---|
| positionMillis | number | The desired position of playback in milliseconds. |
| tolerances(optional) | AVPlaybackTolerance | The tolerances are used only on iOS (more details). |
This is equivalent to playbackObject.setStatusAsync({ positionMillis }).
Promise<AVPlaybackStatus>| Parameter | Type | Description |
|---|---|---|
| progressUpdateIntervalMillis | number | The new minimum interval in milliseconds between calls of |
This is equivalent to playbackObject.setStatusAsync({ progressUpdateIntervalMillis }).
Promise<AVPlaybackStatus>| Parameter | Type | Description |
|---|---|---|
| rate | number | The desired playback rate of the media. This value must be between |
| shouldCorrectPitch | boolean | A boolean describing if we should correct the pitch for a changed rate. If set to |
| pitchCorrectionQuality(optional) | PitchCorrectionQuality | iOS time pitch algorithm setting, defaults to |
This is equivalent to playbackObject.setStatusAsync({ rate, shouldCorrectPitch, pitchCorrectionQuality }).
Promise<AVPlaybackStatus>| Parameter | Type | Description |
|---|---|---|
| volume | number | A number between |
| audioPan(optional) | number | A number between |
This is equivalent to playbackObject.setStatusAsync({ volume, audioPan }).
Note: audioPan is currently only supported on Android using androidImplementation: 'MediaPlayer'
Promise<AVPlaybackStatus>This is equivalent to playbackObject.setStatusAsync({ shouldPlay: false, positionMillis: 0 }).
Promise<AVPlaybackStatus>Unloads the media from memory. loadAsync() must be called again in order to be able to play the media.
This cleanup function will be automatically called in the
Videocomponent'scomponentWillUnmount.
Promise<AVPlaybackStatus>A Promise that is fulfilled with the AVPlaybackStatus of the playbackObject once it is unloaded, or rejects if unloading failed.
Types
Object passed to the onMetadataUpdate function.
| Property | Type | Description |
|---|---|---|
| title(optional) | string | A string with the title of the sound object. |
Literal Type: union
The following forms of source are supported:
- A dictionary of the form
AVPlaybackSourceObject. TheoverrideFileExtensionAndroidproperty may come in handy if the player receives an URL likeexample.com/playwhich redirects toexample.com/player.m3u8. Setting this property tom3u8would allow the Android player to properly infer the content type of the media and use proper media file reader. require('path/to/file')for a media file asset in the source code directory.- An
Assetobject for a media file asset.
The iOS developer documentation lists the audio and video formats supported on iOS.
There are two sets of audio and video formats supported on Android: formats supported by ExoPlayer
and formats supported by Android's MediaPlayer.
Expo uses ExoPlayer implementation by default. To use MediaPlayer, add androidImplementation: 'MediaPlayer' to the initial status of the AV object.
Acceptable values are: number | AVPlaybackSourceObject | Asset
One of the possible forms of the AVPlaybackSource.
| Property | Type | Description |
|---|---|---|
| headers(optional) | Record<string, string> | An optional headers object passed in a network request. |
| overrideFileExtensionAndroid(optional) | string | Only for: Android An optional string overriding extension inferred from the URL. |
| uri | string | A network URL pointing to a media file. |
Literal Type: union
This is the structure returned from all playback API calls and describes the state of the playbackObject at that point in time.
It can take a form of AVPlaybackStatusSuccess or AVPlaybackStatusError based on the playbackObject load status.
Acceptable values are: AVPlaybackStatusError | AVPlaybackStatusSuccess
| Property | Type | Description |
|---|---|---|
| androidImplementation(optional) | string | Only for: Android Underlying implementation to use (when set to Note that setting this property takes effect only when the AV object is just being created (toggling its value later will do nothing). |
| error(optional) | string | A string only present if the |
| isLoaded | false | A boolean set to |
| Property | Type | Description |
|---|---|---|
| androidImplementation(optional) | string | Only for: Android Underlying implementation to use (when set to Note that setting this property takes effect only when the AV object is just being created (toggling its value later will do nothing). |
| audioPan | number | The current audio panning value of the audio for this media. |
| didJustFinish | boolean | A boolean describing if the media just played to completion at the time that this status was received.
When the media plays to completion, the function passed in |
| durationMillis(optional) | number | The duration of the media in milliseconds. This is only present if the media has a duration.
|
| isBuffering | boolean | A boolean describing if the media is currently buffering. |
| isLoaded | true | A boolean set to |
| isLooping | boolean | A boolean describing if the media is currently looping. |
| isMuted | boolean | A boolean describing if the audio of this media is currently muted. |
| isPlaying | boolean | A boolean describing if the media is currently playing. |
| pitchCorrectionQuality(optional) | PitchCorrectionQuality | iOS time pitch algorithm setting. See |
| playableDurationMillis(optional) | number | The position until which the media has been buffered into memory. Like |
| positionMillis | number | The current position of playback in milliseconds. |
| progressUpdateIntervalMillis | number | The minimum interval in milliseconds between calls of |
| rate | number | The current rate of the media. |
| seekMillisToleranceAfter(optional) | number | - |
| seekMillisToleranceBefore(optional) | number | - |
| shouldCorrectPitch | boolean | A boolean describing if we are correcting the pitch for a changed rate. |
| shouldPlay | boolean | A boolean describing if the media is supposed to play. |
| uri | string | The location of the media source. |
| volume | number | The current volume of the audio for this media. |
This is the structure passed to setStatusAsync() to modify the state of the playbackObject.
| Property | Type | Description |
|---|---|---|
| androidImplementation(optional) | string | Only for: Android Underlying implementation to use (when set to Note that setting this property takes effect only when the AV object is just being created (toggling its value later will do nothing). |
| audioPan(optional) | number | Only for: Android The current audio panning value of the audio for this media.
|
| isLooping(optional) | boolean | A boolean describing if the media is currently looping. |
| isMuted(optional) | boolean | A boolean describing if the audio of this media is currently muted.
|
| pitchCorrectionQuality(optional) | PitchCorrectionQuality | iOS time pitch algorithm setting. See |
| positionMillis(optional) | number | The current position of playback in milliseconds. |
| progressUpdateIntervalMillis(optional) | number | The minimum interval in milliseconds between calls of |
| rate(optional) | number | Only for: Android API 23+ iOS The current rate of the media. |
| seekMillisToleranceAfter(optional) | number | - |
| seekMillisToleranceBefore(optional) | number | - |
| shouldCorrectPitch(optional) | boolean | A boolean describing if we are correcting the pitch for a changed rate. |
| shouldPlay(optional) | boolean | A boolean describing if the media is supposed to play. |
| volume(optional) | number | The current volume of the audio for this media.
|
| Property | Type | Description |
|---|---|---|
| toleranceMillisAfter(optional) | number | - |
| toleranceMillisBefore(optional) | number | - |
Enums
Check official Apple documentation for more information.
权限
Android
你必须在 app.json 的 expo.android.permissions 数组中添加以下权限。
iOS
本库使用以下用途说明键: