Brain_Arduino/Assets/Scripts/AudioPlayControl.cs

73 lines
1.7 KiB
C#

using System;
using System.Threading.Tasks;
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 OnMP4PlayFinished;
private void Awake()
{
player = GetComponent<VideoPlayer>();
player.playOnAwake = false;
this.gameObject.SetActive(false);
}
public void ResetMP4Index()
{
this.currentMP4Index = -1;
}
private async Task PlayClipThenStop(VideoClip clip)
{
if (this == null || this.gameObject == null)
return;
player.clip = clip;
this.gameObject.SetActive(true);
player.Play();
isPlaying = true;
await Task.Delay((int)(1000 * player.clip.length));
StopPlay();
isPlaying = false;
}
public async Task PlayStartVideo()
{
await PlayClipThenStop(startAudio);
}
public async Task PlayEndVideo()
{
await PlayClipThenStop(endAudio);
}
public void StopPlay()
{
if (this == null || this.gameObject == null)
return;
isPlaying = false;
player.Stop();
this.gameObject.SetActive(false);
}
public bool IsCanPlayMP4()
{
if (currentMP4Index + 1 == mp4Clips.Length)
return false;
return true;
}
public async void PlayMP4()
{
currentMP4Index++;
var needPlayClip = mp4Clips[currentMP4Index];
await PlayClipThenStop(needPlayClip);
OnMP4PlayFinished?.Invoke();
}
}