Brain_Arduino/Assets/Scripts/AudioPlayControl.cs

81 lines
1.9 KiB
C#

using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Video;
[RequireComponent(typeof(VideoPlayer))]
public class AudioPlayControl : MonoBehaviour
{
public VideoClip startAudio;
public VideoClip endAudio;
private VideoPlayer player;
public VideoClip[] mp4Clips;
private int currentMP4Index = -1;
public bool isPlaying = false;
public Action OnPlayFinished;
private void Awake()
{
player = GetComponent<VideoPlayer>();
player.playOnAwake = false;
this.gameObject.SetActive(false);
}
private void OnDisable()
{
this.StopAllCoroutines();
}
public void ResetMP4Index()
{
this.currentMP4Index = -1;
}
Coroutine stopCoroutine;
private void PlayClipThenStop(VideoClip clip)
{
if (this == null || this.gameObject == null)
return;
player.clip = clip;
this.gameObject.SetActive(true);
player.Play();
isPlaying = true;
stopCoroutine = StartCoroutine(WaitForSeconedToStop());
}
IEnumerator WaitForSeconedToStop()
{
yield return new WaitForSeconds((float)player.clip.length);
StopPlay();
}
public void PlayStartVideo()
{
PlayClipThenStop(startAudio);
}
public void PlayEndVideo()
{
PlayClipThenStop(endAudio);
}
public void StopPlay()
{
if (this == null || this.gameObject == null)
return;
isPlaying = false;
player.Stop();
this.gameObject.SetActive(false);
OnPlayFinished?.Invoke();
this.StopAllCoroutines();
}
public bool IsCanPlayMP4()
{
if (currentMP4Index + 1 == mp4Clips.Length)
return false;
return true;
}
public void PlayMP4()
{
currentMP4Index++;
var needPlayClip = mp4Clips[currentMP4Index];
PlayClipThenStop(needPlayClip);
}
}