unity3D 音频播放

为了方便管理,做一个音频管理器

简单代码如下,根据需要进行拓展,主要是说明方法

using UnityEngine;
using System.Collections;

public class AudioManager 
{
    public void Init()
    {
        m_audioContainer = new GameObject("audioContainer");
    }

    public void PlayAudio(string audioName, bool loop = false, int frequency = 1)
    {
        if (m_audioContainer == null)
            Init();
        GameObject audioObj = new GameObject(audioName);
        audioObj.transform.parent = m_audioContainer.transform;

        AudioSource source = audioObj.AddComponent();
        source.playOnAwake = false;
        source.Stop();
        source.clip = GlobalResource.m_audioClip;   //此处可做成配置,根据audioName去查找音频资源//
        source.loop = loop;
        source.volume = 1;   //音量//
        if (!loop)
        {
            DestroyselfByTime destroySelf = source.gameObject.AddComponent();
            destroySelf.LimitTime = frequency * source.clip.length;
        }

        source.Play();
    }

    private GameObject m_audioContainer;    //音效父节点//

    private static AudioManager s_instance;
    private static readonly byte[] c_staticLocker = new byte[0];
    public static AudioManager Instance
    {
        get 
        {
            if (s_instance == null)
            {
                lock (c_staticLocker)
                {
                    s_instance = new AudioManager();
                }
            }
            return s_instance;
        }   
    }
}

其中DestroyselfByTime脚本如下

using UnityEngine;
using System.Collections;

public class DestroyselfByTime : MonoBehaviour 
{
    public delegate void OnFinished(GameObject target);

	void Start ()
    {
        m_runTime = 0;
	}
	
	void Update ()
    {
        m_runTime += Time.deltaTime;
        if (m_runTime > m_limitTime)
        {
            if (OnFinishedCallBack != null)
                OnFinishedCallBack(gameObject);
            if (gameObject != null)
                Destroy(gameObject);
        }
	}

    public OnFinished OnFinishedCallBack;

    public float LimitTime
    {
        get { return m_limitTime; }
        set { m_limitTime = value; }
    }

    private float m_limitTime;
    private float m_runTime=0;
}

音效资源

GlobalResource.m_audioClip = Resources.Load("sound/dd",typeof(AudioClip)) as AudioClip;

最好做成配置的,名称,音量,是否循环等等,在管理里面用容器存起来并标明状态:None,Loading,Playing,Stop,Free等


你可能感兴趣的:(C#,unity3D)