制作一个小的音乐管理器
最终的效果图:
搭建场景
把显示的按钮画面和制作一个视频播放画面
创建一个RenderTexture
调节Size需要和你的视频尺寸要一致。
按钮的排布:
调用代码:
代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;
using MyTool;
using System;
//<summary>
//使用单例模式
//</summary>
public class MyVideoPlayer : Singleton<MyVideoPlayer>
{
public VideoPlayer Video; //播放视频的组件
public VideoClip[] VideoList; //播放视频的列表
private int _playId = 0;
public AudioSource AudioSo;
public GameObject PauseBtn;
private bool IsShow = false;
// Start is called before the first frame update
void Start()
{
AudioSource AudioSo = Video.GetComponent<AudioSource>();
}
public void Play()
{
Video.clip = VideoList[_playId];//指定一个视频文件
Video.SetTargetAudioSource(0,AudioSo);
Video.Play();//播放
}
public void SetVoume(float arg0)
{
Video.GetComponent<AudioSource>().volume = arg0;
}
public void Stop()
{
Video.Stop();
}
public void PauseOrUnPause()
{
if (Video.isPlaying)
{
Video.Pause();//暂停
PauseBtn.SetActive(true);//显示暂停按钮
}
else
{
Video.Play();//恢复
PauseBtn.SetActive(false);
}
}
public string GetMusicName()
{
return VideoList[_playId].name;
}
//<summary>
//上一首
//</summary>
public void Prve()
{
_playId--;
if (_playId < 0)
{
//_playId = 0; //到头了就不能切换了
_playId = VideoList.Length - 1; //切换到最后一首
Debug.Log("到头了");
}
Play();
}
//<summary>
//下一首
//</summary>
public void Next()
{
_playId++;
if (_playId > VideoList.Length - 1)
{
//_playId = ClipList.Length - 1; //到尾了就不能切换了
_playId = 0; //切换到第一首
Debug.Log("到尾了");
}
Play();
}
// Update is called once per frame
void Update()
{
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MyVideoGrame : MonoBehaviour
{
public Button Prevbtn;
public Button Nextbtn;
public Button Pausebtn;
public Button Stopbtn;
public Text TxtInfo;
public Slider VolVideo;
public GameObject ShowSlider;
private bool IsShow;
// Start is called before the first frame update
void Start()
{
Prevbtn.onClick.AddListener(PrevFun);
Nextbtn.onClick.AddListener(NextFun);
Pausebtn.onClick.AddListener(PauseFun);
Stopbtn.onClick.AddListener(StopFun);
VolVideo.onValueChanged.AddListener(VideoVal);
IsShow = false;
}
//<summary>
//显示调节音量
//</summary>
public void ShowVolSlider()
{
IsShow = !IsShow;
if (IsShow)
{
ShowSlider.SetActive(true);
}else
{
ShowSlider.SetActive(false);
}
}
//<summary>
//隐藏调节音量
//</summary>
public void HideVolSlider()
{
ShowSlider.SetActive(false);
}
private void StopFun()
{
MyVideoPlayer.Instance.Stop();
}
private void VideoVal(float arg0)
{
MyVideoPlayer.Instance.SetVoume(arg0);
}
private void PauseFun()
{
MyVideoPlayer.Instance.PauseOrUnPause();
}
private void NextFun()
{
MyVideoPlayer.Instance.Prve();
TxtInfo.text = MyVideoPlayer.Instance.GetMusicName();
}
private void PrevFun()
{
MyVideoPlayer.Instance.Next();
TxtInfo.text = MyVideoPlayer.Instance.GetMusicName();
}
// Update is called once per frame
void Update()
{
}
}