播放音频使用VideoPlayer组件。
首先搭建如下场景,场景中创建一个Sphere.
在Sphere上面添加VideoPlayer组件,并且给VideoClip赋值一个视频(MP4格式)。
给Sphere添加如下脚本:
- public Button but1;
- public Button but2;
- public Button but3;
- public VideoPlayer video;
- void Start () {
- but1 = GameObject.Find("Button1").GetComponent<Button>();
- but1.onClick.AddListener(OnBut1);
- but2 = GameObject.Find("Button2").GetComponent<Button>();
- but2.onClick.AddListener(OnBut2);
- but3 = GameObject.Find("Button3").GetComponent<Button>();
- but3.onClick.AddListener(OnBut3);
- video = gameObject.GetComponent<VideoPlayer>();
- }
- void OnBut1() {
- if (!video.isPlaying)
- {
- video.Play();
- }
- }
- void OnBut2() {
- if (video.isPlaying)
- {
- video.Pause();
- }
- }
- void OnBut3() {
- if (video.isPlaying)
- {
- video.Stop();
- }
- }
运行,小球上面就会播放视频,button可以控制视频的播放,暂停,关闭。