音频管理模块
Contents
SoundMgr
using System.Collections.Generic;
using ProjectBase.Res;
using ProjectBase.SingleBase;
using UnityEngine;
namespace ProjectBase.Sound
{
/// <summary>
/// 声音管理
/// </summary>
public class SoundMgr : Single<SoundMgr>
{
private string mBgmPath = "Audios/";
private string mSoundPath = "Audios/";
private AudioSource mBgm;
private GameObject mBgmObj;
private GameObject mSoundObj;
private Dictionary<string, AudioSource> mSoundDict = new Dictionary<string, AudioSource>();
/// <summary>
/// 修改背景音乐音量
/// </summary>
public void SetBgmVolume(float volume)
{
mBgm.volume = volume;
}
/// <summary>
/// 修改音效音量
/// </summary>
/// <param name="volume"></param>
public void SetSoundsVolume(float volume)
{
foreach (var value in mSoundDict)
{
value.Value.volume = volume;
}
}
/// <summary>
/// 播放背景音乐
/// </summary>
/// <param name="name">音乐名</param>
public void PlayNewBgm(string name)
{
if (mBgmObj == null)
{
mBgmObj = new GameObject("BgmObject");
mBgm = mBgmObj.AddComponent<AudioSource>();
}
ResMgr.Instance.LoadAsync<AudioClip>(mBgmPath + name, (clip) =>
{
mBgm.clip = clip;
mBgm.loop = true;
mBgm.Stop();
mBgm.Play();
});
}
/// <summary>
/// 继续播放当前BGM
/// </summary>
public void PlayBgm()
{
if (mBgm != null && mBgm.isPlaying)
{
mBgm.Play();
}
}
/// <summary>
/// 暂停当前BGM
/// </summary>
public void PauseBgm()
{
if (mBgm != null && mBgm.isPlaying)
{
mBgm.Pause();
}
}
/// <summary>
/// 停止播放BGM
/// </summary>
public void StopBgm()
{
if (mBgm != null && mBgm.isPlaying)
{
mBgm.Stop();
}
}
/// <summary>
/// 播放音效
/// </summary>
/// <param name="name"></param>
/// <param name="loop"></param>
public void PlaySound(string name, bool loop = false)
{
if (mSoundObj == null)
{
mSoundObj = new GameObject("SoundObject");
}
if (mSoundDict.ContainsKey(name))
{
mSoundDict[name].Stop();
mSoundDict[name].Play();
}
else
{
ResMgr.Instance.LoadAsync<AudioClip>(mSoundPath + name, (clip) =>
{
AudioSource audioSource = mSoundObj.AddComponent<AudioSource>();
mSoundDict.Add(name, audioSource);
audioSource.clip = clip;
audioSource.loop = loop;
audioSource.Play();
});
}
}
/// <summary>
/// 停止播放音效
/// </summary>
/// <param name="name"></param>
public void StopSound(string name)
{
if (mSoundDict.ContainsKey(name))
{
mSoundDict[name].Stop();
}
}
/// <summary>
/// 停止播放所有音效
/// </summary>
public void StopSounds()
{
foreach (var value in mSoundDict)
{
value.Value.Stop();
}
}
}
}