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;
    }
}

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

相关推荐
Sitarrrr1 小时前
【Unity】ScriptableObject的应用和3D物体跟随鼠标移动:鼠标放置物体在场景中
3d·unity
极梦网络无忧1 小时前
Unity中IK动画与布偶死亡动画切换的实现
unity·游戏引擎·lucene
逐·風9 小时前
unity关于自定义渲染、内存管理、性能调优、复杂物理模拟、并行计算以及插件开发
前端·unity·c#
_oP_i10 小时前
Unity Addressables 系统处理 WebGL 打包本地资源的一种高效方式
unity·游戏引擎·webgl
Leoysq19 小时前
【UGUI】实现点击注册按钮跳转游戏场景
游戏·unity·游戏引擎·ugui
_oP_i1 天前
unity中 骨骼、纹理和材质关系
unity·游戏引擎·材质
Padid1 天前
Unity SRP学习笔记(二)
笔记·学习·unity·游戏引擎·图形渲染·着色器
Tp_jh1 天前
推荐一款非常好用的C/C++在线编译器
linux·c语言·c++·ide·单片机·unity·云原生
dangoxiba2 天前
[Unity Demo]从零开始制作空洞骑士Hollow Knight第十八集补充:制作空洞骑士独有的EventSystem和InputModule
游戏·unity·c#·游戏引擎·playmaker
无敌最俊朗@2 天前
unity3d————屏幕坐标,GUI坐标,世界坐标的基础注意点
开发语言·学习·unity·c#·游戏引擎