Unity 3D 音乐播放器www异步加载外部资源

最近在做final year project,我有一个服务器,上面的文件下载下来之后会存放在c盘的默认路径里。然后我要把里面的音频文件读取出来,每个mp3文件做一个button ,用来控制播放。

//This script allows you to toggle music to play and stop.
//Assign an AudioSource to a GameObject and attach an Audio Clip in the Audio Source. Attach this script to the GameObject.

using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class MusicPlayer : MonoBehaviour
{
    public AudioSource Sound ;
    int playing = 1;
    int pause = 2;
    int stop = 3;
    public int state = 3;
    
    public void Setup(string Description) {
        StartCoroutine(wwwDownload(Description));
    }
    System.Collections.IEnumerator wwwDownload(string Description) {
        WWW www = new WWW("file://" + Path.Combine(Application.persistentDataPath, SceneTools.AreaNameDefault() + "//" + Description));
        yield return www;


        AudioClip clip = www.GetAudioClip();
        //clip = www.GetAudioClip(false,false,AudioType.MPEG);
        clip = www.GetAudioClip(false, false, AudioType.MPEG);
        clip.name = Description;
        GameObject prefeb_Sound = GameObject.Find("Audio Source");
        GameObject ob = GameObject.Instantiate<GameObject>(prefeb_Sound, new Vector3(0, 0, 0), Quaternion.identity);
        ob.name = "file:" + Description;
        ob.GetComponent<AudioSource>().clip = clip;
        Sound = ob.GetComponent<AudioSource>();
    }
    public void Play()
    {
        Sound.Play();
        state = playing;
    }
    public void PauseAudio() {
        Sound.Pause();
        state = pause;
    }
    public void StopAudio()
    {
        Sound.Stop();
        state = stop;
    }
    public void RestartAudio()
    {
        Sound.Stop();
        Sound.Play();
        state = playing;
    }

}
关键的一点是www 请求网上或本地资源,需要单独写一个函数,是
System.Collections.IEnumerator wwwDownload(string Description) 
这个函数。IEnumerator类型,作为多线程启动函数的参数。

在里面,我们首先处理www加载,其次是利用加载的文件做进一步编程,比如我就把clip 放在新生成的audiosource上面。然后利用

StartCoroutine(wwwDownload(Description));
开始一个新的线程来执行这个函数。

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour {
    private MusicPlayer music;
    //spublic Button yourButton;
    public GameObject AudioCanvas = null;
    public GameObject buttonPrefeb;
    private GameObject newButton = null;
    private bool getName = false;
    private bool setUp = false;
    private String AudioName = "";
    int playing = 1;
    int pause = 2;
    int stop = 3;
    
    public void sendAudioName(String description) {
        AudioName = description;
        getName = true;
    }
    void Start()
    {
        if (this.transform.parent != null) { 
            Debug.Log(this.transform.parent.name);
            AudioCanvas = this.transform.parent.GetChild(this.transform.parent.childCount - 1 ).gameObject;
            newButton = Instantiate(buttonPrefeb) as GameObject;
            newButton.transform.SetParent(AudioCanvas.transform, false);
            music = (GetComponent("MusicPlayer") as MusicPlayer);//获取播放器对象
            if (getName) { 
                music.Setup(AudioName);
                setUp = true;
            }
            Button btn = newButton.GetComponent<Button>();
            //newButton.transform.position = new Vector3(0, 0, 0);
            Debug.Log(newButton.GetComponent<RectTransform>().localPosition);
            newButton.GetComponent<RectTransform>().localPosition = new Vector3(0, 0, 0);
            btn.onClick.AddListener(TaskOnClick);
            newButton.GetComponentInChildren<Text>().text = this.transform.parent.name + " Play >";
        }
    }
     void Update()
    {
        if (getName && !setUp)
        {
            music.Setup(AudioName);
            setUp = true; 

        }
    }
    void TaskOnClick()
    {

        // Debug.Log("AudioName  " + AudioName);
        // Debug.Log("Play"+music.Sound.clip.name);
        // Debug.Log("isPlaying" + music.Sound.isPlaying+music.Sound.isActiveAndEnabled);
        // GameObject musicOb = GameObject.Find("file:" + AudioName);
        //musicOb.GetComponent<AudioSource>().Play();
        // Debug.Log("musicOb" + musicOb.GetComponent<AudioSource>().clip.name + musicOb.GetComponent<AudioSource>().isActiveAndEnabled);
        //music.Play();
        Text textOnbutton = newButton.transform.GetChild(0).gameObject.GetComponent<Text>();
        if (music.Sound.isPlaying == false)
        {
            music.Play();
            if (music.state == playing)
                textOnbutton.text = this.transform.parent.name + "- Pause";

        }

        else
        {
            music.PauseAudio();
            if (music.state == pause)
                textOnbutton.text = this.transform.parent.name + "- Play";
        }
    }

    //void OnGUI()
    //{

    //    if (music.state == stop || music.state == pause)
    //    {
    //        if (GUI.Button(new Rect(10, 10, 100, 50), "PLAY"))
    //        {

    //            Debug.Log("Play!");
    //            music.Play();//调用播放器Play方法

    //        }
    //        if (music.state == pause)
    //            if (GUI.Button(new Rect(120, 10, 100, 50), "Stop"))
    //            {

    //                Debug.Log("Stop!");
    //                music.StopAudio();

    //            }

    //    }
    //    else if (music.state == playing) {
    //        if (GUI.Button(new Rect(10, 10, 100, 50), "PAUSE"))
    //        {

    //            Debug.Log("Pause!");
    //            music.PauseAudio();

    //        }
    //        if (GUI.Button(new Rect(120, 10, 100, 50), "Stop"))
    //        {

    //            Debug.Log("Stop!");
    //            music.StopAudio();

    //        }

    //    }


    //}

}
 music = (GetComponent("MusicPlayer") as MusicPlayer);//获取播放器对
我们首先要创建一个空物体,把两个脚本放上去,然后问题来了,两个脚本都是mono的,怎么才能传递参数呢。 
 

关键就是利用getcomponent函数获取脚本,然后调用脚本的函数,貌似不可以直接修改脚本的属性,有兴趣的可以自己试试。

然后可以用ongui来设置屏幕上的gui按钮并判断是否按下按钮,也可以利用canvas新建一个新的画布再加上button,

btn.onClick.AddListener(TaskOnClick);
利用这行代码给button绑定一个函数,一般是控制音乐播放的。


大家看我的代码就好,如果有问题可以留言。

猜你喜欢

转载自blog.csdn.net/weixin_39673686/article/details/79250792