Brain_Arduino/Assets/Scripts/AudioPlayControl.cs

73 lines
1.7 KiB
C#
Raw Normal View History

2024-12-01 15:24:10 +08:00
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;
2024-12-01 18:19:57 +08:00
public VideoClip[] mp4Clips;
private int currentMP4Index = -1;
public bool isPlaying = false;
public Action OnMP4PlayFinished;
2024-12-01 15:24:10 +08:00
private void Awake()
{
player = GetComponent<VideoPlayer>();
player.playOnAwake = false;
2024-12-01 18:19:57 +08:00
this.gameObject.SetActive(false);
2024-12-01 15:24:10 +08:00
}
2024-12-01 18:19:57 +08:00
public void ResetMP4Index()
2024-12-01 15:24:10 +08:00
{
2024-12-01 18:19:57 +08:00
this.currentMP4Index = -1;
}
private async Task PlayClipThenStop(VideoClip clip)
{
if (this == null || this.gameObject == null)
return;
player.clip = clip;
2024-12-01 15:24:10 +08:00
this.gameObject.SetActive(true);
player.Play();
2024-12-01 18:19:57 +08:00
isPlaying = true;
2024-12-01 15:24:10 +08:00
await Task.Delay((int)(1000 * player.clip.length));
2024-12-01 18:19:57 +08:00
StopPlay();
isPlaying = false;
}
public async Task PlayStartVideo()
{
await PlayClipThenStop(startAudio);
2024-12-01 15:24:10 +08:00
}
2024-12-01 18:19:57 +08:00
public async Task PlayEndVideo()
2024-12-01 15:24:10 +08:00
{
2024-12-01 18:19:57 +08:00
await PlayClipThenStop(endAudio);
2024-12-01 15:24:10 +08:00
}
public void StopPlay()
{
2024-12-01 18:19:57 +08:00
if (this == null || this.gameObject == null)
return;
isPlaying = false;
2024-12-01 15:24:10 +08:00
player.Stop();
this.gameObject.SetActive(false);
}
2024-12-01 18:19:57 +08:00
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();
}
2024-12-01 15:24:10 +08:00
}