接手了前同事们的一个元宇宙的项目,里面有各楼层不同的背景音乐,人物的一些动作音效,一些书籍音频,语音问答,投屏语音通信,靠近播放视频等,需要对音频做各种播放、暂停、切换、停止等操作,但原代码没有对音频没有进行统一管理,散落在脚本各处,难以维护,就写一个统一的管理框架。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class WAudioManager : MonoBehaviour
{public static WAudioManager Instance;//...... 可以继续根据需求添加AudioSource,多的话也可以用数组管理....... public AudioSource bgAudioResource; //背景音乐public AudioSource effectAudioResource;//音效public AudioSource bookAudioResource; //听书private void Awake(){if (Instance == null){Instance = this;}else{Destroy(gameObject);}}/// <summary>/// 播放背景音乐/// </summary>/// <param name="clip"></param>public void PlayBackgroundAudio(AudioClip clip){if (clip!=null && bgAudioResource.clip != clip){bgAudioResource.loop = true;bgAudioResource.clip = clip;bgAudioResource.Play();}}/// <summary>/// 设置音量/// </summary>/// <param name="volume"></param>public void SetBackgroundAudioVolume(float volume){bgAudioResource.volume = volume;}public void PauseBackgroundAudio(){bgAudioResource.Pause();}public void UnPauseBackgroundAudio(){bgAudioResource.UnPause();}public void StopBackgroundAudio(){bgAudioResource.Stop();}/// <summary>/// 播放音效/// </summary>/// <param name="clip"></param>public void PlayEffectAudio(AudioClip clip){if (clip != null){effectAudioResource.clip = clip;effectAudioResource.Play();}}/// <summary>/// 设置音效音量/// </summary>/// <param name="volume"></param>public void SetEffectAudioVolume(float volume){effectAudioResource.volume = volume;}public void PauseEffectAudio(){effectAudioResource.Pause();}public void UnPauseEffectAudio(){effectAudioResource.UnPause();}public void StopEffectAudio(){effectAudioResource.Stop();}}