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

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

相关推荐
向宇it15 小时前
【unity小技巧】unity 什么是反射?反射的作用?反射的使用场景?反射的缺点?常用的反射操作?反射常见示例
开发语言·游戏·unity·c#·游戏引擎
Heaphaestus,RC16 小时前
【Unity3D】获取 GameObject 的完整层级结构
unity·c#
芋芋qwq16 小时前
Unity UI射线检测 道具拖拽
ui·unity·游戏引擎
tealcwu17 小时前
【Unity服务】关于Unity LevelPlay的基本情况
unity·游戏引擎
大眼睛姑娘20 小时前
Unity3d场景童话梦幻卡通Q版城镇建筑植物山石3D模型游戏美术素材
unity·游戏美术
鹿野素材屋1 天前
Unity Dots下的动画合批工具:GPU ECS Animation Baker
unity·游戏引擎
小春熙子1 天前
Unity图形学之着色器之间传递参数
unity·游戏引擎·技术美术·着色器
Java Fans2 天前
在Unity中实现电梯升降功能的完整指南
unity·游戏引擎
GrimRaider2 天前
[Unity]TileMap开发,TileMap地图缝隙问题
unity·游戏引擎·tilemap
无敌最俊朗@2 天前
unity3d——基础篇小项目(开始界面)
unity·游戏引擎