유니티의 VideoPlayer
컴포넌트를 이용하여 유튜브와 유사한 비디오 플레이어를 구현한 스크립트
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;
namespace Video
{
public class VideoController : MonoBehaviour
{
[Header("Audio Source")] [SerializeField]
private AudioSource audioSource;
[Header("Video Player")] [SerializeField]
private VideoPlayer videoPlayer;
[Header("Control Parts")] [SerializeField]
private Button startPauseButton;
[SerializeField] private Slider speedSlider;
[SerializeField] private Slider volumeSlider;
[SerializeField] private Toggle loopToggle;
[SerializeField] private Slider videoSlider;
// private bool _isPlaying;
// private float _currentSpeed;
// private bool _loop;
#region Unity Methods
private void Start()
{
// add event to parts
AddListeners();
// Set VideoPlayer default values
videoPlayer.SetTargetAudioSource(0, audioSource);
volumeSlider.value = videoPlayer.GetDirectAudioVolume(0);
SetVideoSpeed(1f);
SetVideoVolume(1f);
SetLoop(false);
videoPlayer.Prepare();
}
private void Update()
{
videoSlider.SetValueWithoutNotify((float)(videoPlayer.time / videoPlayer.length));
}
private void OnDestroy()
{
RemoveListeners();
}
#endregion
#region Video Controlling Methods
public void PlayPause()
{
if (videoPlayer.isPlaying)
{
videoPlayer.Pause();
}
else
{
if (!videoPlayer.isPrepared)
{
videoPlayer.Prepare();
return;
}
videoPlayer.Play();
}
}
public void PlayPause(bool isPlay)
{
if (!isPlay)
{
videoPlayer.Pause();
}
else
{
if (!videoPlayer.isPrepared)
{
videoPlayer.Prepare();
return;
}
videoPlayer.Play();
}
}
public void SetVideoVolume(float value)
{
videoPlayer.SetDirectAudioVolume(0, value);
volumeSlider.SetValueWithoutNotify(value);
}
public void SetVideoSpeed(float value)
{
videoPlayer.playbackSpeed = value;
speedSlider.SetValueWithoutNotify(value);
}
public void SetLoop(bool value)
{
videoPlayer.isLooping = value;
loopToggle.isOn = value;
}
public void SetPlayTime(float time)
{
var duration = videoPlayer.frameCount / (ulong)videoPlayer.frameRate;
videoPlayer.time = time * duration;
}
#endregion
#region Util Methods
public void AddListeners()
{
startPauseButton.onClick.AddListener(PlayPause);
speedSlider.onValueChanged.AddListener(SetVideoSpeed);
volumeSlider.onValueChanged.AddListener(SetVideoVolume);
loopToggle.onValueChanged.AddListener(SetLoop);
videoSlider.onValueChanged.AddListener(SetPlayTime);
}
public void RemoveListeners()
{
startPauseButton.onClick.RemoveAllListeners();
speedSlider.onValueChanged.RemoveAllListeners();
volumeSlider.onValueChanged.RemoveAllListeners();
loopToggle.onValueChanged.RemoveAllListeners();
videoSlider.onValueChanged.RemoveAllListeners();
}
#endregion
}
}