VideoPlayer

class in UnityEngine.Video

/

Inherits from:Behaviour

Switch to Manual

Description

将视频内容播放到目标上。

Content can be either a VideoClip imported asset or a URL such as file:// or http://. Video content will be projected onto one of the supported targets, such as camera background or RenderTexture. If the video content includes transparency, this transparency will be present in the target, allowing objects behind the video target to be visible. When the data VideoPlayer.source is set to URL, the audio and video description of what is being played will only be initialized once the VideoPlayer preparation is completed. This can be tested with VideoPlayer.isPrepared.

电影文件格式支持说明

VideoPlayer 在其实现中使用原生音频和视频解码库,您有责任使用符合目标平台要求的视频。VideoClipImporter 提供了一个将 VideoClip 资源转码为 H.264VP8 视频编解码器的选项,以及一些实验性选项(例如 Resolution)。这会将匹配的编解码器用于音频轨道:分别是 AACVorbis

另请参阅:VideoClipImporter.SetTargetSettingsVideoImporterTargetSettings.enableTranscoding

您可以选择忽略此转码,而是改用已知受目标系统支持的视频,同时使用外部程序更精确地控制编码过程。在使用过程中,VideoClipImporter 编辑器会提供指导和警告,以更好地帮助您做出正确的格式和编码选择。

For now, vendor recommendations must be followed, and are especially constrained on older mobile platforms. For example, videos you find on the web will often require inspection and manipulations before they can be used reliably in the context of a game running on multiple devices. The following are examples of recommendations and known limitations:

* Android: Supported Media Formats. See additional notes below.
* Windows: H.264 Video Decoder (see Format Constraints)
* iPhone 6-7: Compare iPhone Models (see TV and Video)

可用于硬件加速的本机支持的最优视频编解码器是 H.264,同时 VP8 作为可以在需要时使用的软件解码解决方案。在 Android 上,VP8 还支持使用本机库,因此也可以根据型号对硬件进行辅助。要在编码参数中查找的键值:

* Video Codec: H.264 or VP8.
* Resolution: For example: 1280 x 720.
* Profile: Applicable for H.264. The profile is a set of capabilities and constraints; vendors often specify this, such as "Baseline" or "Main". See here.
* Profile Level: Applicable for H.264. Within a given profile, the level specifies certain performance requirements such as "Baseline 3.1". See here.
* Audio Codec: Typically AAC (with mp4 videos using H.264) or Vorbis (with webm videos using VP8).
* Audio Channels: depends on platform. For example, the Android recommendation is for stereo files, but many devices will accept 5.1.

关于 Android 的注意事项

* Support for resolutions above 640 x 360 is not available on all devices. Runtime checks are done to verify this and failures will cause the movie to not be played.
* For Jelly Bean/MR1, movies above 1280 x 720 or with more than 2 audio tracks will not be played due to bugs in the OS libraries.
* For Lollipop and above, any resolution or number of audio channels may be attempted, but will be constrained by device capabilities.
* The Vulkan graphics API is not yet supported.
* Format compatibility issues are reported in the adb logcat output and are always prefixed with AndroidVideoMedia.
* Also pay attention to device-specific error messages located near Unity's error messages: they are not available to the engine, but often explain what the compatibility issue is.
* Playback from asset bundles is only supported for uncompressed bundles, read directly from disk.

以下部分演示了 VideoPlayer 的一些功能:

// Examples of VideoPlayer function

using UnityEngine;

public class Example : MonoBehaviour { void Start() { // Will attach a VideoPlayer to the main camera. GameObject camera = GameObject.Find("Main Camera");

// VideoPlayer automatically targets the camera backplane when it is added // to a camera object, no need to change videoPlayer.targetCamera. var videoPlayer = camera.AddComponent<UnityEngine.Video.VideoPlayer>();

// Play on awake defaults to true. Set it to false to avoid the url set // below to auto-start playback since we're in Start(). videoPlayer.playOnAwake = false;

// By default, VideoPlayers added to a camera will use the far plane. // Let's target the near plane instead. videoPlayer.renderMode = UnityEngine.Video.VideoRenderMode.CameraNearPlane;

// This will cause our Scene to be visible through the video being played. videoPlayer.targetCameraAlpha = 0.5F;

// Set the video to play. URL supports local absolute or relative paths. // Here, using absolute. videoPlayer.url = "/Users/graham/movie.mov";

// Skip the first 100 frames. videoPlayer.frame = 100;

// Restart from beginning when done. videoPlayer.isLooping = true;

// Each time we reach the end, we slow down the playback by a factor of 10. videoPlayer.loopPointReached += EndReached;

// Start playback. This means the VideoPlayer may have to prepare (reserve // resources, pre-load a few frames, etc.). To better control the delays // associated with this preparation one can use videoPlayer.Prepare() along with // its prepareCompleted event. videoPlayer.Play(); }

void EndReached(UnityEngine.Video.VideoPlayer vp) { vp.playbackSpeed = vp.playbackSpeed / 10.0F; } }

MovieTexture Migration Notes

Since the VideoPlayer is fundamentally different from the legacy movie playback solution MovieTexture, we are providing a few examples to help you migrate your project using MovieTexture to the new VideoPlayer solution.

Playing the Movie Example :

MovieTexture :

using UnityEngine;

public class PlayMovieMT : MonoBehaviour { public AudioClip movieAudioClip; public MovieTexture movieTexture;

void Start() { var audioSource = gameObject.AddComponent<AudioSource>(); audioSource.clip = movieAudioClip; }

void Update() { if (Input.GetButtonDown("Jump")) { var audioSource = GetComponent<AudioSource>(); GetComponent<Renderer>().material.mainTexture = movieTexture;

if (movieTexture.isPlaying) { movieTexture.Pause(); audioSource.Pause(); } else { movieTexture.Play(); audioSource.Play(); } } } }

VideoPlayer :

using UnityEngine;

public class PlayMovieVP : MonoBehaviour { public UnityEngine.Video.VideoClip videoClip;

void Start() { var videoPlayer = gameObject.AddComponent<UnityEngine.Video.VideoPlayer>(); var audioSource = gameObject.AddComponent<AudioSource>();

videoPlayer.playOnAwake = false; videoPlayer.clip = videoClip; videoPlayer.renderMode = UnityEngine.Video.VideoRenderMode.MaterialOverride; videoPlayer.targetMaterialRenderer = GetComponent<Renderer>(); videoPlayer.targetMaterialProperty = "_MainTex"; videoPlayer.audioOutputMode = UnityEngine.Video.VideoAudioOutputMode.AudioSource; videoPlayer.SetTargetAudioSource(0, audioSource); }

void Update() { if (Input.GetButtonDown("Jump")) { var vp = GetComponent<UnityEngine.Video.VideoPlayer>();

if (vp.isPlaying) { vp.Pause(); } else { vp.Play(); } } } }

Downloading a Movie Example :

MovieTexture :

using UnityEngine;

public class DownloadMovieMT : MonoBehaviour { void Start() { StartCoroutine(GetMovieTexture()); }

IEnumerator GetMovieTexture() { using (var uwr = UnityWebRequestMultimedia.GetMovieTexture("http://myserver.com/mymovie.ogv")) { yield return uwr.SendWebRequest(); if (uwr.isNetworkError || uwr.isHttpError) { Debug.LogError(uwr.error); yield break; }

MovieTexture movie = DownloadHandlerMovieTexture.GetContent(uwr);

GetComponent<Renderer>().material.mainTexture = movie; movie.loop = true; movie.Play(); } } }

VideoPlayer :

using UnityEngine;

public class DownloadMovieVP : MonoBehaviour { void Start() { var vp = gameObject.AddComponent<UnityEngine.Video.VideoPlayer>(); vp.url = "http://myserver.com/mymovie.mp4";

vp.isLooping = true; vp.renderMode = UnityEngine.Video.VideoRenderMode.MaterialOverride; vp.targetMaterialRenderer = GetComponent<Renderer>(); vp.targetMaterialProperty = "_MainTex";

vp.Play(); } }

Static Variables

controlledAudioTrackMaxCountMaximum number of audio tracks that can be controlled. (Read Only)

Variables

aspectRatio定义如何拉伸视频内容以填充目标区域。
audioOutputMode嵌入在视频中的音频的目标。
audioTrackCountNumber of audio tracks found in the data source currently configured. (Read Only)
canSetDirectAudioVolume当前平台和视频格式是否支持直接输出音量控制。(只读)
canSetPlaybackSpeed播放速度是否可以更改。(只读)
canSetSkipOnDropWhether frame-skipping to maintain synchronization can be controlled. (Read Only)
canSetTime是否可以使用 time 或 timeFrames 属性更改当前时间。(只读)
canSetTimeSourceWhether the time source followed by the VideoPlayer can be changed. (Read Only)
canStepReturns true if the VideoPlayer can step forward through the video content. (Read Only)
clipThe clip being played by the VideoPlayer.
clockTimeThe clock time that the VideoPlayer follows to schedule its samples. The clock time is expressed in seconds. (Read Only)
controlledAudioTrackCountNumber of audio tracks that this VideoPlayer will take control of.
externalReferenceTime VideoPlayer 用于纠正其偏差的外部时钟的参考时间。
frameThe frame index of the currently available frame in VideoPlayer.texture.
frameCountNumber of frames in the current video content. (Read Only)
frameRateThe frame rate of the clip or URL in frames/second. (Read Only)
heightThe height of the images in the VideoClip, or URL, in pixels. (Read Only)
isLoopingDetermines whether the VideoPlayer restarts from the beginning when it reaches the end of the clip.
isPausedWhether playback is paused. (Read Only)
isPlaying是否正在播放内容。(只读)
isPreparedWhether the VideoPlayer has successfully prepared the content to be played. (Read Only)
lengthThe length of the VideoClip, or the URL, in seconds. (Read Only)
pixelAspectRatioDenominatorDenominator of the pixel aspect ratio (num:den) for the VideoClip or the URL. (Read Only)
pixelAspectRatioNumeratorNumerator of the pixel aspect ratio (num:den) for the VideoClip or the URL. (Read Only)
playbackSpeed基本播放速率的增加倍数。
playOnAwake内容是否会在组件被唤醒后立即开始播放。
renderMode将绘制视频内容的位置。
sendFrameReadyEvents启用 frameReady 事件。
skipOnDropWhether the VideoPlayer is allowed to skip frames to catch up with current time.
sourceThe source that the VideoPlayer uses for playback.
targetCamera Camera component to draw to when VideoPlayer.renderMode is set to either VideoRenderMode.CameraFarPlane or VideoRenderMode.CameraNearPlane.
targetCamera3DLayout源视频媒体中包含的 3D 内容的类型。
targetCameraAlpha目标摄像机平面视频的整体透明度级别。
targetMaterialProperty Material texture property which is targeted when VideoPlayer.renderMode is set to Video.VideoTarget.MaterialOverride.
targetMaterialRenderer在 VideoPlayer.renderMode 设置为 Video.VideoTarget.MaterialOverride 时被设为目标的 Renderer
targetTexture当 VideoPlayer.renderMode 设置为 Video.VideoTarget.RenderTexture 时,要在其中绘制资源的 RenderTexture。
textureInternal texture in which video content is placed. (Read Only)
timeThe presentation time of the currently available frame in VideoPlayer.texture.
timeReference VideoPlayer 对其进行观测以发现和纠正偏差的时钟。
timeSource[NOT YET IMPLEMENTED] The source used used by the VideoPlayer to derive its current time.
urlThe file or HTTP URL that the VideoPlayer reads content from.
waitForFirstFrameDetermines whether the VideoPlayer will wait for the first frame to be loaded into the texture before starting playback when VideoPlayer.playOnAwake is on.
widthThe width of the images in the VideoClip, or URL, in pixels. (Read Only)

Public Functions

EnableAudioTrackEnable/disable audio track decoding. Only effective when the VideoPlayer is not currently playing.
GetAudioChannelCount指定音频轨道中的音频声道数。
GetAudioLanguageCode返回指定轨道的语言代码(如果有)。
GetAudioSampleRateGets the audio track sampling rate in Hertz.
GetDirectAudioMuteGets the direct-output audio mute status for the specified track.
GetDirectAudioVolume返回指定轨道的直接输出音量。
GetTargetAudioSource获取当 VideoPlayer.audioOutputMode 设置为 VideoAudioOutputMode.AudioSource 时将接收指定轨道的音频样本的 AudioSource。
IsAudioTrackEnabledWhether decoding for the specified audio track is enabled. See VideoPlayer.EnableAudioTrack for distinction with mute.
Pause暂停播放并保持当前时间不变。
Play开始播放。
PrepareInitiates playback engine preparation.
SetDirectAudioMute设置指定轨道的直接输出音频静音状态。
SetDirectAudioVolume设置指定轨道的直接输出音频音量。
SetTargetAudioSource设置当使用 VideoPlayer.audioOutputMode 选择此音频目标时将接收指定轨道的音频样本的 AudioSource。
StepForward立即将当前时间向前推进一帧。
StopStops the playback and sets the current time to 0.

Events

clockResyncOccurredInvoked when the VideoPlayer clock is synced back to its VideoTimeReference.
errorReceived通过此回调报告 HTTP 连接问题等错误。
frameDropped[尚未实现] 当视频解码器在播放期间没有按照时间源生成帧时调用。
frameReady当新帧准备就绪时调用。
loopPointReachedInvoked when the VideoPlayer reaches the end of the content to play.
prepareCompletedInvoked when the VideoPlayer preparation is complete.
seekCompleted在搜寻操作完成后调用。
started在调用 Play 后立即调用。

Delegates

ErrorEventHandlerDelegate type for VideoPlayer events that contain an error message.
EventHandlerDelegate type for all parameterless events emitted by VideoPlayers.
FrameReadyEventHandlerDelegate type for VideoPlayer events that carry a frame number.
TimeEventHandler带有时间位置的 VideoPlayer 事件的委托类型。

Inherited members

Variables

enabled启用的 Behaviour 可更新,禁用的 Behaviour 不可更新。
isActiveAndEnabledHas the Behaviour had active and enabled called?
gameObject此组件附加到的游戏对象。始终将组件附加到游戏对象。
tag此游戏对象的标签。
transform附加到此 GameObject 的 Transform。
hideFlagsShould the object be hidden, saved with the Scene or modifiable by the user?
name对象的名称。

Public Functions

BroadcastMessage调用此游戏对象或其任何子项中的每个 MonoBehaviour 上名为 methodName 的方法。
CompareTag此游戏对象是否使用 tag 进行了标记?
GetComponent如果游戏对象附加了类型为 type 的组件,则将其返回,否则返回 null。
GetComponentInChildren使用深度首次搜索返回 GameObject 或其任何子项中类型为 type 的组件。
GetComponentInParent返回 GameObject 或其任何父项中类型为 type 的组件。
GetComponents返回 GameObject 中类型为 type 的所有组件。
GetComponentsInChildren返回 GameObject 或其任何子项中类型为 type 的所有组件。
GetComponentsInParent返回 GameObject 或其任何父项中类型为 type 的所有组件。
SendMessage调用此游戏对象中的每个 MonoBehaviour 上名为 methodName 的方法。
SendMessageUpwards调用此游戏对象中的每个 MonoBehaviour 上或此行为的每个父级上名为 methodName 的方法。
GetInstanceID返回对象的实例 ID。
ToString返回 GameObject 的名称。

Static Functions

Destroy删除 GameObject、组件或资源。
DestroyImmediate立即销毁对象 /obj/。强烈建议您改用 Destroy。
DontDestroyOnLoadDo not destroy the target Object when loading a new Scene.
FindObjectOfType返回第一个类型为 type 的已加载的激活对象。
FindObjectsOfType返回所有类型为 type 的已加载的激活对象的列表。
Instantiate克隆 original 对象并返回克隆对象。

Operators

bool该对象是否存在?
operator !=比较两个对象是否引用不同的对象。
operator ==比较两个对象引用,判断它们是否引用同一个对象。