一个通用库,为音频和视频播放提供单独的 API。
Audio.Sound
对象和 Video
组件共享用于媒体播放的统一命令式 API。
¥The Audio.Sound
objects and Video
components share a unified imperative API for media playback.
请注意,对于 Video
,所有操作也可以通过组件上的 props 进行。但是,我们建议对大多数需要对视频播放状态进行更精细控制的应用使用此命令式播放 API。
¥Note that for Video
, all of the operations are also available via props on the component. However, we recommend using this imperative playback API for most applications where finer control over the state of the video playback is needed.
有关 Audio.Sound
和 Video
的播放 API 的示例,请参阅 播放列表示例应用。
¥See the playlist example app for an example on the playback API for both Audio.Sound
and Video
.
信息 tvOS(Apple TV)上不提供录音 API。
¥Audio recording APIs are not available on tvOS (Apple TV).
¥Installation
-
npx expo install expo-av
If you are installing this in an existing React Native app (bare workflow), start by installing expo
in your project. Then, follow the additional instructions as mentioned by library's README under "Installation in bare React Native projects" section.
¥Configuration in app.json/app.config.js
如果你在项目中使用配置插件(EAS 构建 或 npx expo run:[android|ios]
),则可以使用其内置的 配置插件 配置 expo-av
。该插件允许你配置无法在运行时设置的各种属性,并且需要构建新的应用二进制文件才能生效。
¥You can configure expo-av
using its built-in config plugin if you use config plugins in your project (EAS Build or npx expo run:[android|ios]
). The plugin allows you to configure various properties that cannot be set at runtime and require building a new app binary to take effect.
{
"expo": {
"plugins": [
[
"expo-av",
{
"microphonePermission": "Allow $(PRODUCT_NAME) to access your microphone."
}
]
]
}
}
Name | Default | Description |
---|---|---|
microphonePermission | "Allow $(PRODUCT_NAME) to access your microphone" | Only for: iOS A string to set the |
了解如何在 expo-av
存储库中的安装说明 文件中配置原生项目。
¥Learn how to configure the native projects in the installation instructions in the expo-av
repository.
¥Usage
在这个页面上,我们引用了 playbackObject
上的操作。以下是获取声音和视频参考的访问权限的示例:
¥On this page, we reference operations on playbackObject
s. Here is an example of obtaining access to the reference for both sound and video:
Audio.Sound
¥Example: Audio.Sound
await Audio.setAudioModeAsync({ playsInSilentModeIOS: true });
const playbackObject = new Audio.Sound();
// OR
const { sound: playbackObject } = await Audio.Sound.createAsync(
{ uri: 'http://foo/bar.mp3' },
{ shouldPlay: true }
);
有关 Audio.Sound.createAsync()
的更多信息,请参阅 音频文档。
¥See the audio documentation for further information on Audio.Sound.createAsync()
.
Video
¥Example: Video
%%placeholder-start%%... %%placeholder-end%%
_handleVideoRef = component => {
const playbackObject = component;
...
}
%%placeholder-start%%... %%placeholder-end%%
render() {
return (
<Video
ref={this._handleVideoRef}
/>
%%placeholder-start%%... %%placeholder-end%%
)
}
请参阅 视频文档 了解更多信息。
¥See the video documentation for further information.
setOnPlaybackStatusUpdate()
¥Example: setOnPlaybackStatusUpdate()
_onPlaybackStatusUpdate = playbackStatus => {
if (!playbackStatus.isLoaded) {
// Update your UI for the unloaded state
if (playbackStatus.error) {
console.log(`Encountered a fatal error during playback: ${playbackStatus.error}`);
// Send Expo team the error on Slack or the forums so we can help you debug!
}
} else {
// Update your UI for the loaded state
if (playbackStatus.isPlaying) {
// Update your UI for the playing state
} else {
// Update your UI for the paused state
}
if (playbackStatus.isBuffering) {
// Update your UI for the buffering state
}
if (playbackStatus.didJustFinish && !playbackStatus.isLooping) {
// The player has just finished playing and will stop. Maybe you want to play something else?
}
%%placeholder-start%%... %%placeholder-end%%
}
};
// Load the playbackObject and obtain the reference.
playbackObject.setOnPlaybackStatusUpdate(this._onPlaybackStatusUpdate);
¥Example: Loop media exactly 20 times
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 });
// Load the playbackObject and obtain the reference.
playbackObject.setOnPlaybackStatusUpdate(this._onPlaybackStatusUpdate);
playbackObject.setIsLooping(true);
¥What is seek tolerance and why would I want to use it [iOS only]
当被要求寻找 A/V 项目时,iOS 中的原生播放器有时可能会寻找略有不同的时间。苹果文档 中提到的这种技术用于缩短 seekTo
调用的时间(播放器可以决定从与请求的时间不同的时间立即播放,而不是解码确切的请求部分并以解码延迟播放)。
¥When asked to seek an A/V item, native player in iOS sometimes may seek to a slightly different time. This technique, mentioned in Apple documentation, is used to shorten the time of the seekTo
call (the player may decide to play immediately from a different time than requested, instead of decoding the exact requested part and playing it with the decoding delay).
如果精度很重要,你可以指定玩家寻求的容差。然而,这将导致延迟增加。
¥If precision is important, you can specify the tolerance with which the player will seek. However, this will result in an increased delay.
import { Audio, Video } from 'expo-av';
AV._DEFAULT_INITIAL_PLAYBACK_STATUS
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()
.
AV
AV Methods
getStatusAsync()
Gets the AVPlaybackStatus
of the playbackObject
.
A Promise
that is fulfilled with the AVPlaybackStatus
of the playbackObject
.
setStatusAsync(status)
Name | 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.
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
.
Playback
Extends: AV
On the playbackObject
reference, the following API is provided.
Playback Methods
loadAsync(source, initialStatus, downloadAsync)
Name | 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.
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
.
playAsync()
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
.
playFromPositionAsync(positionMillis, tolerances)
Name | 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
.
replayAsync(status)
Name | 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.
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.
setIsLoopingAsync(isLooping)
Name | Type | Description |
---|---|---|
isLooping | boolean | A boolean describing if the media should play once ( |
This is equivalent to playbackObject.setStatusAsync({ isLooping })
.
setIsMutedAsync(isMuted)
Name | Type | Description |
---|---|---|
isMuted | boolean | A boolean describing if the audio of this media should be muted. |
This is equivalent to playbackObject.setStatusAsync({ isMuted })
.
setPositionAsync(positionMillis, tolerances)
Name | 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 })
.
setProgressUpdateIntervalAsync(progressUpdateIntervalMillis)
Name | Type | Description |
---|---|---|
progressUpdateIntervalMillis | number | The new minimum interval in milliseconds between calls of |
This is equivalent to playbackObject.setStatusAsync({ progressUpdateIntervalMillis })
.
setRateAsync(rate, shouldCorrectPitch, pitchCorrectionQuality)
Name | 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 })
.
setVolumeAsync(volume, audioPan)
Name | 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'
stopAsync()
This is equivalent to playbackObject.setStatusAsync({ shouldPlay: false, positionMillis: 0 })
.
unloadAsync()
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
Video
component'scomponentWillUnmount
.
A Promise
that is fulfilled with the AVPlaybackStatus
of the playbackObject
once it is unloaded, or rejects if unloading failed.
AVMetadata
Object passed to the onMetadataUpdate
function.
Name | Type | Description |
---|---|---|
title (optional) | string | A string with the title of the sound object. |
AVPlaybackSource
Literal Type: multiple types
The following forms of source are supported:
AVPlaybackSourceObject
.
The overrideFileExtensionAndroid
property may come in handy if the player receives an URL like example.com/play
which redirects to example.com/player.m3u8
.
Setting this property to m3u8
would 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.Asset
object 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
AVPlaybackSourceObject
One of the possible forms of the AVPlaybackSource
.
Name | 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. |
AVPlaybackStatus
Literal Type: multiple types
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
AVPlaybackStatusError
Name | 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 |
AVPlaybackStatusSuccess
Name | 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. |
AVPlaybackStatusToSet
This is the structure passed to setStatusAsync()
to modify the state of the playbackObject
.
Name | 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.
|
AVPlaybackTolerance
Name | Type | Description |
---|---|---|
toleranceMillisAfter (optional) | number | - |
toleranceMillisBefore (optional) | number | - |
PitchCorrectionQuality
Check official Apple documentation for more information.
PitchCorrectionQuality Values
¥Permissions
¥Android
你必须将以下权限添加到 expo.android.permissions
数组内的 app.json 中。
¥You must add the following permissions to your app.json inside the expo.android.permissions
array.
Android Permission | Description |
---|---|
Allows an application to record audio. |
¥iOS
该库使用以下用法描述键:
¥The following usage description keys are used by this library:
Info.plist Key | Description |
---|---|
A message that tells the user why the app is requesting access to the device’s microphone. |