Brain_Arduino/Assets/Scripts/AudioPlayControl.cs

81 lines
1.9 KiB
C#
Raw Permalink Normal View History

2024-12-01 15:24:10 +08:00
using System;
2024-12-04 17:21:36 +08:00
using System.Collections;
2024-12-01 15:24:10 +08:00
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;
2024-12-04 17:21:36 +08:00
public Action OnPlayFinished;
2024-12-01 18:19:57 +08:00
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-04 17:21:36 +08:00
private void OnDisable()
{
this.StopAllCoroutines();
}
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;
}
2024-12-04 17:21:36 +08:00
Coroutine stopCoroutine;
private void PlayClipThenStop(VideoClip clip)
2024-12-01 18:19:57 +08:00
{
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-04 17:21:36 +08:00
stopCoroutine = StartCoroutine(WaitForSeconedToStop());
}
IEnumerator WaitForSeconedToStop()
{
yield return new WaitForSeconds((float)player.clip.length);
2024-12-01 18:19:57 +08:00
StopPlay();
}
2024-12-04 17:21:36 +08:00
public void PlayStartVideo()
2024-12-01 18:19:57 +08:00
{
2024-12-04 17:21:36 +08:00
PlayClipThenStop(startAudio);
2024-12-01 15:24:10 +08:00
}
2024-12-04 17:21:36 +08:00
public void PlayEndVideo()
2024-12-01 15:24:10 +08:00
{
2024-12-04 17:21:36 +08:00
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-04 17:21:36 +08:00
OnPlayFinished?.Invoke();
this.StopAllCoroutines();
2024-12-01 15:24:10 +08:00
}
2024-12-01 18:19:57 +08:00
public bool IsCanPlayMP4()
{
if (currentMP4Index + 1 == mp4Clips.Length)
return false;
return true;
}
2024-12-04 17:21:36 +08:00
public void PlayMP4()
2024-12-01 18:19:57 +08:00
{
currentMP4Index++;
var needPlayClip = mp4Clips[currentMP4Index];
2024-12-04 17:21:36 +08:00
PlayClipThenStop(needPlayClip);
2024-12-01 18:19:57 +08:00
}
2024-12-01 15:24:10 +08:00
}