Unity框架学习--音频管理器

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 音频管理器
/// </summary>
public class AudioManager : SingletonMonoAutoBase1_DonDestoryOnLoad<AudioManager>
{
    //各个声道的AudioSource组件
    AudioSource bgmAudioSource;
    AudioSource bgsAudioSource;
    AudioSource voiceAudioSource;

    //各个声道的游戏对象
    GameObject bgmController;
    GameObject soundController;

    GameObject sound2D;
    GameObject sound3D;

    GameObject bgsController;
    GameObject msController;
    GameObject voiceController;

    //控制器的名字
    string bgmControllerName = "BGMController";
    string soundControllerName = "SoundController";
    string soundPool2DName = "SoundPool2D";
    string soundClip2DName = "SoundClip2D";
    string soundClip3DName = "SoundClip3D";
    string soundPool3DName = "SoundPool3D";
    string bgsControllerName = "BGSController";
    string msControllerName = "MSController";
    string voiceControllerName = "VoiceController";

    /// <summary>
    /// 播放音乐
    /// </summary>
    public void PlayBGM(AudioClip bgm,bool loop=true)
    {
        if (bgm == null) return;

        bgmAudioSource.clip = bgm;
        bgmAudioSource.loop = loop;
        bgmAudioSource.Play();
    }

    /// <summary>
    /// 暂停BGM
    /// </summary>
    public void PauseBGM()
    {
        bgmAudioSource.Pause();
    }

    /// <summary>
    /// 取消暂停BGM
    /// </summary>
    public void UnPauseBGM()
    {
        bgmAudioSource.UnPause();
    }

    /// <summary>
    /// 停止BGM
    /// </summary>
    public void StopBGM()
    {
        bgmAudioSource.Stop();
        bgmAudioSource.clip = null;
    }

    /// <summary>
    /// 播放指定的音效--2D音效
    /// </summary>
    public void PlaySound(AudioClip sound)
    {
        if (sound == null)
        {
            Debug.LogWarning("传入的文件为空!");
            return;
        }

        //临时的空物体,用来播放音效
        GameObject go = null;

        for (int i = 0; i < sound2D.transform.childCount; i++)
        {
            if (sound2D.transform.GetChild(i).gameObject.activeSelf)
            {
                go = sound2D.transform.GetChild(i).gameObject;
                go.SetActive(true);
                break;
            }
        }

        if (go == null)
        {
            go = new GameObject(soundClip2DName);
            go.transform.SetParent(sound2D.transform);
        }

        //如果该游戏对象身上没有AudioSource组件,则添加AudioSource组件并设置参数
        if (!go.TryGetComponent<AudioSource>(out AudioSource audioSource))
        {
            go.AddComponent<AudioSource>();
            audioSource.playOnAwake = false;
            audioSource.loop = false;
        }

        //设置要播放的音效
        audioSource.clip = sound;

        StartCoroutine(DestroyWhenFinished());

        //每隔一秒检测一次,如果该音效播放完毕,则销毁音效的游戏对象
        IEnumerator DestroyWhenFinished()
        {
            do
            {
                yield return new WaitForSeconds(1);
            } while (audioSource!=null && audioSource.time > 0);

            if (go != null)
            {
                go.SetActive(false);
                audioSource.clip = null;
            }
        }

    }

    /// <summary>
    /// 播放3D音效
    /// </summary>
    public void PlaySound(AudioClip sound,GameObject target)
    {
        if (sound == null)
        {
            Debug.LogWarning("传入的文件为空!");
            return;
        }

        if (target == null)
        {
            Debug.LogWarning("传入的target为空!");
            return;
        }

        //临时的空物体,用来播放音效
        GameObject go = null;

        //如果对象池中有,则从对象池中取出来用
        for (int i = 0; i < sound3D.transform.childCount; i++)
        {
            if (!sound3D.transform.GetChild(i).gameObject.activeSelf)
            {
                go = sound3D.transform.GetChild(i).gameObject;
                go.SetActive(true);
                break;
            }
        }
        //如果对象池中没有,则创建一个游戏对象
        if (go == null)
        {
            go = new GameObject(soundClip3DName);
        }

        go.transform.SetParent(target.transform);
        go.transform.localPosition = Vector3.zero;

        if (go.TryGetComponent<AudioSource>(out AudioSource audioSource))
        {
            audioSource = go.AddComponent<AudioSource>();
            audioSource.playOnAwake = false;
            audioSource.loop = false;
            audioSource.spatialBlend = 1f;  //3D效果,近大远小
        }

        //设置要播放的音频
        audioSource.clip = sound;

        audioSource.Play();

        StartCoroutine(DestroyWhenFinsh());

        IEnumerator DestroyWhenFinsh()
        {
            do
            {
                yield return new WaitForSeconds(1);
            } while (audioSource.time > 0);
        }

        if (go != null)
        {
            //放入对象池
            go.transform.SetParent(sound3D.transform);
            go.transform.localPosition = Vector3.zero;
            audioSource.clip = null;
            go.SetActive(false);
        }
    }

    /// <summary>
    /// 在世界空间中指定的位置播放3D音效
    /// </summary>
    public void PlaySound(AudioClip sound,Vector3 worldPosition,Transform parent=null)
    {
        if (sound == null)
        {
            return;
        }

        GameObject go = null;
        for (int i = 0; i < sound3D.transform.childCount; i++)
        {
            if (sound3D.transform.GetChild(i).gameObject.activeSelf)
            {
                go = sound3D.transform.GetChild(i).gameObject;
                go.SetActive(true);
                break;
            }
        }
        if (go==null)
        {
            go = new GameObject(soundClip3DName);
        }

        go.transform.position = worldPosition;
        go.transform.SetParent(parent);

        if (!go.TryGetComponent<AudioSource>(out AudioSource audioSource))
        {
            audioSource = go.AddComponent<AudioSource>();
            audioSource.playOnAwake = false;
            audioSource.loop = false;
            audioSource.spatialBlend = 1f;
        }

        audioSource.clip = sound;

        audioSource.Play();

        StartCoroutine(DestroyWhenFinshed());

        IEnumerator DestroyWhenFinshed()
        {
            do
            {
                yield return new WaitForSeconds(1);
            } while (audioSource!=null && audioSource.time > 0);

            if (go != null)
            {
                go.transform.SetParent(sound3D.transform);
                go.transform.localPosition = Vector3.zero;
                audioSource.clip = null;
                go.SetActive(false);

            }
        }


    }

    /// <summary>
    /// 播放环境音效
    /// </summary>
    public void PlayBGS(AudioClip bgs,bool loop=true)
    {
        if (bgs==null)
        {
            return;
        }

        bgsAudioSource.loop = loop;
        bgsAudioSource.clip = bgs;
        bgsAudioSource.Play();
    }

    /// <summary>
    /// 暂停环境音效
    /// </summary>
    public void PauseBGS()
    {
        bgsAudioSource.Pause();
    }

    /// <summary>
    /// 取消暂停环境音效
    /// </summary>
    public void UnPause()
    {
        bgsAudioSource.UnPause();
    }

    /// <summary>
    /// 停止BGS
    /// </summary>
    public void StopBGS()
    {
        bgsAudioSource.Stop();
        bgsAudioSource.clip = null;
    }

    private void Awake()
    {
        //创建并设置背景音乐的控制器
        bgmController = CreateController(bgmControllerName, transform);
        bgmAudioSource = bgmController.AddComponent<AudioSource>();
        bgmAudioSource.playOnAwake = false;
        bgmAudioSource.loop = true;

        //创建音效控制器
        soundController = CreateController(soundControllerName, transform);
        sound2D = CreateController(soundPool2DName, soundController.transform);
        sound3D = CreateController(soundPool3DName, soundController.transform);

        bgsController = CreateController(bgsControllerName, transform);  //环境音效
        bgsAudioSource = bgsController.AddComponent<AudioSource>();
        bgsAudioSource.playOnAwake = false;
        bgsAudioSource.loop = true;

        msController = CreateController(msControllerName, transform);  //提示音效

        voiceController = CreateController(voiceControllerName,transform);  //角色语音
        voiceAudioSource = voiceController.AddComponent<AudioSource>();
        voiceAudioSource.loop = false;
        voiceAudioSource.playOnAwake = false;

    }

    GameObject CreateController(string name,Transform parent)
    {
        GameObject go = new GameObject(name);
        go.transform.SetParent(parent);
        return go;
    }
}

很多代码写的大差不差的,完全可以精简

相关推荐
神码编程4 小时前
【Unity功能集】TextureShop纹理工坊(五)选区
unity·游戏引擎·shader·ps选区
m0_7482517210 小时前
Android webview 打开本地H5项目(Cocos游戏以及Unity游戏)
android·游戏·unity
benben04410 小时前
Unity3D仿星露谷物语开发7之事件创建动画
unity·游戏引擎
林枫依依12 小时前
Unity2021.3.16f1可以正常打开,但是Unity2017.3.0f3却常常打开闪退或者Unity2017编辑器运行起来就闪退掉
unity
异次元的归来1 天前
Unity DOTS中的share component
unity·游戏引擎
向宇it1 天前
【从零开始入门unity游戏开发之——C#篇25】C#面向对象动态多态——virtual、override 和 base 关键字、抽象类和抽象方法
java·开发语言·unity·c#·游戏引擎
_oP_i1 天前
unity webgl部署到iis报错
unity
Go_Accepted1 天前
Unity全局雾效
unity
向宇it1 天前
【从零开始入门unity游戏开发之——C#篇24】C#面向对象继承——万物之父(object)、装箱和拆箱、sealed 密封类
java·开发语言·unity·c#·游戏引擎
每日出拳老爷子1 天前
【图形渲染】【Unity Shader】【Nvidia CG】有用的参考资料链接
unity·游戏引擎·图形渲染