Version: 2018.2

VideoPlayer

class in UnityEngine.Video

/

継承:Behaviour

マニュアルに切り替える

説明

Plays video content onto a target.

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.

Movie File Format Support Notes

The VideoPlayer uses native audio and video decoding libraries in its implementation and it is your responsibility to use videos that match the requirements for the target platform. The VideoClipImporter offers an option to transcode the VideoClip assets into one of H.264 or VP8 video codecs, along with a few options to experiment with, such as resolution. This uses the matching codec for audio tracks: AAC and Vorbis respectively.

See Also: VideoClipImporter.SetTargetSettings and VideoImporterTargetSettings.enableTranscoding.

You may choose to omit this transcoding and instead use videos that you already know are supported by the target systems, keeping finer control over the encoding process using an external program. Over time, the VideoClipImporter editor will provide guidelines and warnings to better help making proper format and encoding choices.

For now, vendor recommendations must be followed, and are especially constrained on older mobile platforms. For instance, 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)

The best natively supported video codec for hardware acceleration is H.264, with VP8 being a software decoding solution that can be used when required. On Android, VP8 is also supported using native libraries and as such may also be hardware-assisted depending on models. Key values to look for in your encoding parameters:

* 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 Notes

* 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 ones: they are not available to the engine, but often explains what the compatibility issue is.

The following demonstrates a few features of the 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 :

public class PlayMovie : 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 :

public class PlayMovie : MonoBehaviour
{
    public VideoClip videoClip;

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

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

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

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

Downloading a Movie Example :

MovieTexture :

public class DownloadMovie : 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 :

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

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

vp.Play(); } }

Static 変数

controlledAudioTrackMaxCountMaximum number of audio tracks that can be controlled.

変数

aspectRatioDefines how the video content will be stretched to fill the target area.
audioOutputModeDestination for the audio embedded in the video.
audioTrackCountNumber of audio tracks found in the data source currently configured.
canSetDirectAudioVolumeWhether direct-output volume controls are supported for the current platform and video format. (Read Only)
canSetPlaybackSpeedWhether the playback speed can be changed. (Read Only)
canSetSkipOnDropDetermines whether the VideoPlayer skips frames to catch up with current time. (Read Only)
canSetTimeWhether current time can be changed using the time or timeFrames property. (Read Only)
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.
controlledAudioTrackCountNumber of audio tracks that this VideoPlayer will take control of. The other ones will be silenced. A maximum of 64 tracks are allowed. The actual number of audio tracks cannot be known in advance when playing URLs, which is why this value is independent of the VideoPlayer.audioTrackCount property.
externalReferenceTimeReference time of the external clock the VideoPlayer uses to correct its drift.
frameThe frame index currently being displayed by the VideoPlayer.
frameCountNumber of frames in the current video content.
frameRateThe frame rate of the clip or URL in frames/second. (Read Only).
isLoopingDetermines whether the VideoPlayer restarts from the beginning when it reaches the end of the clip.
isPlayingWhether content is being played. (Read Only)
isPreparedWhether the VideoPlayer has successfully prepared the content to be played. (Read Only)
playbackSpeedFactor by which the basic playback rate will be multiplied.
playOnAwakeWhether the content will start playing back as soon as the component awakes.
renderModeWhere the video content will be drawn.
sendFrameReadyEventsEnables the frameReady events.
skipOnDropWhether the VideoPlayer is allowed to skip frames to catch up with current time.
sourceThe source that the VideoPlayer uses for playback.
targetCameraCamera component to draw to when VideoPlayer.renderMode is set to either VideoRenderMode.CameraFarPlane or VideoRenderMode.CameraNearPlane.
targetCamera3DLayoutType of 3D content contained in the source video media.
targetCameraAlphaOverall transparency level of the target camera plane video.
targetMaterialPropertyMaterial texture property which is targeted when VideoPlayer.renderMode is set to Video.VideoTarget.MaterialOverride.
targetMaterialRenderer Renderer which is targeted when VideoPlayer.renderMode is set to Video.VideoTarget.MaterialOverride
targetTexture RenderTexture to draw to when VideoPlayer.renderMode is set to Video.VideoTarget.RenderTexture.
textureInternal texture in which video content is placed.
timeThe VideoPlayer current time in seconds.
timeReferenceThe clock that the VideoPlayer observes to detect and correct drift.
timeSource[NOT YET IMPLEMENTED] The source used used by the VideoPlayer to derive its current time.
urlThe file or HTTP URL that the VideoPlayer will read 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.

Public 関数

EnableAudioTrackEnable/disable audio track decoding. Only effective when the VideoPlayer is not currently playing.
GetAudioChannelCountThe number of audio channels in the specified audio track.
GetAudioLanguageCodeReturns the language code, if any, for the specified track.
GetDirectAudioMuteGet the direct-output audio mute status for the specified track.
GetDirectAudioVolumeReturn the direct-output volume for specified track.
GetTargetAudioSourceGets the AudioSource that will receive audio samples for the specified track if VideoPlayer.audioOutputMode is set to VideoAudioOutputMode.AudioSource.
IsAudioTrackEnabledReturns whether decoding for the specified audio track is enabled. See VideoPlayer.EnableAudioTrack for distinction with mute.
PausePauses the playback and leaves the current time intact.
PlayStarts playback.
PrepareInitiates playback engine prepration.
SetDirectAudioMuteSet the direct-output audio mute status for the specified track.
SetDirectAudioVolumeSet the direct-output audio volume for the specified track.
SetTargetAudioSourceSets the AudioSource that will receive audio samples for the specified track if this audio target is selected with VideoPlayer.audioOutputMode.
StepForwardAdvances the current time by one frame immediately.
StopPauses the playback and sets the current time to 0.

Events

clockResyncOccurredInvoked when the VideoPlayer's clock is synced back to its VideoTimeReference.
errorReceivedErrors such as HTTP connection problems are reported through this callback.
frameDropped[NOT YET IMPLEMENTED] Invoked when the video decoder does not produce a frame as per the time source during playback.
frameReadyInvoked when a new frame is ready.
loopPointReachedInvoked when the VideoPlayer reaches the end of the content to play.
prepareCompletedInvoked when the VideoPlayer preparation is complete.
seekCompletedInvoke after a seek operation completes.
startedInvoked immediately after Play is called.

デリゲート

ErrorEventHandlerDelegate type for VideoPlayer events that contain an error message.
EventHandlerDelegate type for all parameter-less events emitted by VideoPlayers.
FrameReadyEventHandlerDelegate type for VideoPlayer events that carry a frame number.
TimeEventHandlerDelegate type for VideoPlayer events that carry a time position.

継承メンバー

変数

enabled有効であれば更新され、無効であれば更新されません。
isActiveAndEnabledBehaviour が有効かどうか
gameObjectこのコンポーネントはゲームオブジェクトにアタッチされます。コンポーネントはいつもゲームオブジェクトにアタッチされています。
tagゲームオブジェクトのタグ
transformThe Transform attached to this GameObject.
hideFlagsShould the object be hidden, saved with the Scene or modifiable by the user?
nameオブジェクト名

Public 関数

BroadcastMessageゲームオブジェクトまたは子オブジェクトにあるすべての MonoBehaviour を継承したクラスにある methodName 名のメソッドを呼び出します。
CompareTagこのゲームオブジェクトは tag とタグ付けされているかどうか
GetComponentゲームオブジェクトに type がアタッチされている場合は 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 を返します
ToStringReturns the name of the GameObject.

Static 関数

Destroyゲームオブジェクトやコンポーネント、アセットを削除します
DestroyImmediateDestroys the object obj immediately. You are strongly recommended to use Destroy instead.
DontDestroyOnLoadDo not destroy the target Object when loading a new Scene.
FindObjectOfTypeタイプ type から最初に見つけたアクティブのオブジェクトを返します
FindObjectsOfTypeタイプから見つけたすべてのアクティブのオブジェクト配列を返します
Instantiateoriginal のオブジェクトをクローンします

Operator

boolオブジェクトが存在するかどうか
operator !=二つのオブジェクトが異なるオブジェクトを参照しているか比較します
operator ==2つのオブジェクト参照が同じオブジェクトを参照しているか比較します。
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961