Unity声音管理

public class AudioManager : MonoBehaviour {

 

    //[SerializeField]
    //private AudioClip[] audios;
   
    private Dictionary audios;

    [SerializeField]
    private AudioClip audioBg;

    [SerializeField]
    private AudioSource BgAudioSource;

    [SerializeField]
    private AudioSource NormalAudioSource;

 

    public static AudioManager Instance
    {
        get;
        protected set;
    }

    private void Awake()
    {
        Instance = this;
        audios = new Dictionary();
        AudioClip[] audioArray = Resources.LoadAll("Audio");//声音路径
        foreach (AudioClip item in audioArray)
        {
            audios.Add(item.name, item);
        }
    }

 

    public void PlayBgSource(string soundName)
    {
        if (audios.ContainsKey(soundName))
        {
            PlaySound(BgAudioSource, audios[soundName], 0.5f, true);

        }
    }

    public void PlayNormalSource(string soundName)
    {
        if (audios.ContainsKey(soundName))
        {
            PlaySound(NormalAudioSource, audios[soundName], 1f, false);

        }
    }

    private void PlaySound(AudioSource audioSource, AudioClip clip, float volum, bool loop = false)
    {
        audioSource.clip = clip;
        audioSource.volume = volum;
        audioSource.loop = loop;
        audioSource.Play();
    }

    public float GetAudioTime(Transform _obj)
    {
        float result = ((Component)_obj).GetComponent().clip.length + 0.2f;
        if ((Object)((Component)_obj).GetComponent() == (Object)null)
        {
            return 0f;
        }
        return result;
    }

    public float GetAudioTime()
    {
        return this.NormalAudioSource.clip.length + 0.2f;
    }
    private void OnDestroy()
    {
        audios.Clear();
    }
}

你可能感兴趣的:(u3d)