一、组件的获取
/// <summary>
/// MediaPlayer对象
/// </summary>
private MediaPlayer myMediaPlayer;
private void Awake()
{
myMediaPlayer = videoPlayObj.GetComponent<MediaPlayer>();
}
二、控制的API
-
暂停:myMediaPlayer.Control.Pause()
-
播放:myMediaPlayer.Control.Play()
-
跳到指定位置:myMediaPlayer.Control.Seek(60)
seek的时候,可以传入double时间进度或者指定的帧位置
关于seek的官方源码api说明(part):
/// <summary>
/// The time in seconds seeked will be to the exact time
/// This can take a long time is the keyframes are far apart
/// Some platforms don't support this and instead seek to the closest keyframe
/// </summary>
void Seek(double time);
/// <summary>
/// The time in seconds seeked will be to the closest keyframe
/// </summary>
void SeekFast(double time);
/// <summary>
/// The time in seconds seeked to will be within the range [time-timeDeltaBefore, time+timeDeltaAfter] for efficiency.
/// Only supported on macOS, iOS and tvOS.
/// Other platforms will automatically pass through to Seek()
/// </summary>
void SeekWithTolerance(double time, double timeDeltaBefore, double timeDeltaAfter);
/// <summary>
/// Seek to a specific frame, range is [0, GetMaxFrameNumber()]
/// NOTE: For best results the video should be encoded as keyframes only
/// and have no audio track, or an audio track with the same length as the video track
/// </summary>
void SeekToFrame(int frame, float overrideFrameRate = 0f);
/// <summary>
/// Seek forwards or backwards relative to the current frame
/// NOTE: For best results the video should be encoded as keyframes only
/// and have no audio track, or an audio track with the same length as the video track
/// </summary>
void SeekToFrameRelative(int frameOffset, float overrideFrameRate = 0f);
三、进度的计算
Debug.Log($"总长度:{myMediaPlayer.Info.GetDuration()} 当前进度:myMediaPlayer.Control.GetCurrentTime()}");
四、测试案例
代码清单
#if UNITY_EDITOR
[ContextMenu("测试播放功能-跳转播放")]
#endif
void testPlayer()
{
Func<UniTask> TestDemo = async () =>
{
Debug.Log("等待5秒钟...");
await UniTask.Delay(TimeSpan.FromSeconds(5.0f));
Debug.Log("暂停");
myMediaPlayer.Control.Pause();
Debug.Log("等待5秒钟...");
await UniTask.Delay(TimeSpan.FromSeconds(3.0f));
Debug.Log("跳到20秒处,并播放");
myMediaPlayer.Control.Seek(20);
myMediaPlayer.Control.Play();
Debug.Log("等待5秒钟...");
await UniTask.Delay(TimeSpan.FromSeconds(5.0f));
myMediaPlayer.Control.Pause();
Debug.Log("暂停,并跳到60秒处,再次播放");
myMediaPlayer.Control.Seek(60);
myMediaPlayer.Control.Play();
};
TestDemo();
}