本方法是对Ez-Sound-Manager的扩展

https://github.com/JackM36/Eazy-Sound-Manager

参考Audio Toolkit Free Version

http://unity.clockstone.com/

SoundManager
 using System;
using UnityEngine;
using System.Collections.Generic; namespace ZStudio.SoundManager
{
public class SoundManager : MonoBehaviour
{
private static SoundManager _instance = null;
private static float vol = 1f;
private static float musicVol = 1f;
private static float soundsVol = 1f;
private static float UISoundsVol = 1f; private static Dictionary<int, Audio> musicAudio;
private static Dictionary<int, Audio> soundsAudio;
private static Dictionary<int, Audio> UISoundsAudio; private static bool initialized = false; private static SoundManager instance
{
get
{
if (_instance == null)
{
_instance = (SoundManager)FindObjectOfType(typeof(SoundManager));
if (_instance == null)
{
// Create gameObject and add component
_instance = (new GameObject("ZSoundManager")).AddComponent<SoundManager>();
}
}
return _instance;
}
} /// <summary>
/// The gameobject that the sound manager is attached to
/// </summary>
public static GameObject gameobject { get { return instance.gameObject; } } /// <summary>
/// When set to true, new Audios that have the same audio clip as any other Audio, will be ignored
/// </summary>
public static bool ignoreDuplicateMusic { get; set; } /// <summary>
/// When set to true, new Audios that have the same audio clip as any other Audio, will be ignored
/// </summary>
public static bool ignoreDuplicateSounds { get; set; } /// <summary>
/// When set to true, new Audios that have the same audio clip as any other Audio, will be ignored
/// </summary>
public static bool ignoreDuplicateUISounds { get; set; } /// <summary>
/// Global volume
/// </summary>
public static float globalVolume
{
get
{
return vol;
}
set
{
vol = value;
}
} /// <summary>
/// Global music volume
/// </summary>
public static float globalMusicVolume
{
get
{
return musicVol;
}
set
{
musicVol = value;
}
} /// <summary>
/// Global sounds volume
/// </summary>
public static float globalSoundsVolume
{
get
{
return soundsVol;
}
set
{
soundsVol = value;
}
} /// <summary>
/// Global UI sounds volume
/// </summary>
public static float globalUISoundsVolume
{
get
{
return UISoundsVol;
}
set
{
UISoundsVol = value;
}
} void Awake()
{
instance.Init();
} void Update()
{
List<int> keys; // Update music
keys = new List<int>(musicAudio.Keys);
for (var i = ; i < keys.Count; i++)
{
int key = keys[i];
Audio _audio = musicAudio[key];
_audio.Update(); // Remove all music clips that are not playing
if (!_audio.playing && !_audio.paused)
{
if (_audio.onComletelyPlayed != null)
_audio.onComletelyPlayed.Invoke(_audio);
Destroy(_audio.audioSource);
musicAudio.Remove(key);
}
} // Update sound fx
keys = new List<int>(soundsAudio.Keys);
for (var i = ; i < keys.Count; i++)
{
int key = keys[i];
Audio _audio = soundsAudio[key];
_audio.Update(); // Remove all sound fx clips that are not playing
if (!_audio.playing && !_audio.paused)
{
if (_audio.onComletelyPlayed != null)
_audio.onComletelyPlayed.Invoke(_audio);
Destroy(_audio.audioSource);
soundsAudio.Remove(key);
}
} // Update UI sound fx
keys = new List<int>(UISoundsAudio.Keys);
for (var i = ; i < keys.Count; i++)
{
int key = keys[i];
Audio _audio = UISoundsAudio[key];
_audio.Update(); // Remove all UI sound fx clips that are not playing
if (!_audio.playing && !_audio.paused)
{
if (_audio.onComletelyPlayed != null)
_audio.onComletelyPlayed.Invoke(_audio);
Destroy(_audio.audioSource);
UISoundsAudio.Remove(key);
}
}
} void Init()
{
if (!initialized)
{
musicAudio = new Dictionary<int, Audio>();
soundsAudio = new Dictionary<int, Audio>();
UISoundsAudio = new Dictionary<int, Audio>(); ignoreDuplicateMusic = false;
ignoreDuplicateSounds = false;
ignoreDuplicateUISounds = false; initialized = true;
DontDestroyOnLoad(this);
}
} #region GetAudio Functions /// <summary>
/// Returns the Audio that has as its id the audioID if one is found, returns null if no such Audio is found
/// </summary>
/// <param name="audioID">The id of the Audio to be retrieved</param>
/// <returns>Audio that has as its id the audioID, null if no such Audio is found</returns>
public static Audio GetAudio(int audioID)
{
Audio audio; audio = GetMusicAudio(audioID);
if (audio != null)
{
return audio;
} audio = GetSoundAudio(audioID);
if (audio != null)
{
return audio;
} audio = GetUISoundAudio(audioID);
if (audio != null)
{
return audio;
} return null;
} /// <summary>
/// Returns the first occurrence of Audio that plays the given audioClip. Returns null if no such Audio is found
/// </summary>
/// <param name="audioClip">The audio clip of the Audio to be retrieved</param>
/// <returns>First occurrence of Audio that has as plays the audioClip, null if no such Audio is found</returns>
public static Audio GetAudio(AudioClip audioClip)
{
Audio audio = GetMusicAudio(audioClip);
if (audio != null)
{
return audio;
} audio = GetSoundAudio(audioClip);
if (audio != null)
{
return audio;
} audio = GetUISoundAudio(audioClip);
if (audio != null)
{
return audio;
} return null;
} /// <summary>
/// Returns the music Audio that has as its id the audioID if one is found, returns null if no such Audio is found
/// </summary>
/// <param name="audioID">The id of the music Audio to be returned</param>
/// <returns>Music Audio that has as its id the audioID if one is found, null if no such Audio is found</returns>
public static Audio GetMusicAudio(int audioID)
{
List<int> keys = new List<int>(musicAudio.Keys);
foreach (int key in keys)
{
if (audioID == key)
{
return musicAudio[key];
}
} return null;
} /// <summary>
/// Returns the first occurrence of music Audio that plays the given audioClip. Returns null if no such Audio is found
/// </summary>
/// <param name="audioClip">The audio clip of the music Audio to be retrieved</param>
/// <returns>First occurrence of music Audio that has as plays the audioClip, null if no such Audio is found</returns>
public static Audio GetMusicAudio(AudioClip audioClip)
{
List<int> keys;
keys = new List<int>(musicAudio.Keys);
foreach (int key in keys)
{
Audio audio = musicAudio[key];
if (audio.clip == audioClip)
{
return audio;
}
} return null;
} /// <summary>
/// Returns the sound fx Audio that has as its id the audioID if one is found, returns null if no such Audio is found
/// </summary>
/// <param name="audioID">The id of the sound fx Audio to be returned</param>
/// <returns>Sound fx Audio that has as its id the audioID if one is found, null if no such Audio is found</returns>
public static Audio GetSoundAudio(int audioID)
{
List<int> keys = new List<int>(soundsAudio.Keys);
foreach (int key in keys)
{
if (audioID == key)
{
return soundsAudio[key];
}
} return null;
} /// <summary>
/// Returns the first occurrence of sound Audio that plays the given audioClip. Returns null if no such Audio is found
/// </summary>
/// <param name="audioClip">The audio clip of the sound Audio to be retrieved</param>
/// <returns>First occurrence of sound Audio that has as plays the audioClip, null if no such Audio is found</returns>
public static Audio GetSoundAudio(AudioClip audioClip)
{
List<int> keys;
keys = new List<int>(soundsAudio.Keys);
foreach (int key in keys)
{
Audio audio = soundsAudio[key];
if (audio.clip == audioClip)
{
return audio;
}
} return null;
} /// <summary>
/// Returns the UI sound fx Audio that has as its id the audioID if one is found, returns null if no such Audio is found
/// </summary>
/// <param name="audioID">The id of the UI sound fx Audio to be returned</param>
/// <returns>UI sound fx Audio that has as its id the audioID if one is found, null if no such Audio is found</returns>
public static Audio GetUISoundAudio(int audioID)
{
List<int> keys = new List<int>(UISoundsAudio.Keys);
foreach (int key in keys)
{
if (audioID == key)
{
return UISoundsAudio[key];
}
} return null;
} /// <summary>
/// Returns the first occurrence of UI sound Audio that plays the given audioClip. Returns null if no such Audio is found
/// </summary>
/// <param name="audioClip">The audio clip of the UI sound Audio to be retrieved</param>
/// <returns>First occurrence of UI sound Audio that has as plays the audioClip, null if no such Audio is found</returns>
public static Audio GetUISoundAudio(AudioClip audioClip)
{
List<int> keys;
keys = new List<int>(UISoundsAudio.Keys);
foreach (int key in keys)
{
Audio audio = UISoundsAudio[key];
if (audio.clip == audioClip)
{
return audio;
}
} return null;
} #endregion #region Play Functions /// <summary>
/// Play background music
/// </summary>
/// <param name="clip">The audio clip to play</param>
/// <param name="onCompletelyPlayed">The audio play completed</param>
/// <returns>The ID of the created Audio object</returns>
public static int PlayMusic(AudioClip clip, Action<Audio> onCompletelyPlayed)
{
return PlayMusic(clip, 1f, false, false, 1f, 1f, -1f, null, onCompletelyPlayed);
} /// <summary>
/// Play background music
/// </summary>
/// <param name="clip">The audio clip to play</param>
/// <param name="volume"> The volume the music will have</param>
/// <param name="onCompletelyPlayed">The audio play completed</param>
/// <returns>The ID of the created Audio object</returns>
public static int PlayMusic(AudioClip clip, float volume, Action<Audio> onCompletelyPlayed)
{
return PlayMusic(clip, volume, false, false, 1f, 1f, -1f, null, onCompletelyPlayed);
} /// <summary>
/// Play background music
/// </summary>
/// <param name="clip">The audio clip to play</param>
/// <param name="volume"> The volume the music will have</param>
/// <param name="loop">Wether the music is looped</param>
/// <param name = "persist" > Whether the audio persists in between scene changes</param>
/// <param name="onCompletelyPlayed">The audio play completed</param>
/// <returns>The ID of the created Audio object</returns>
public static int PlayMusic(AudioClip clip, float volume, bool loop, bool persist, Action<Audio> onCompletelyPlayed)
{
return PlayMusic(clip, volume, loop, persist, 1f, 1f, -1f, null, onCompletelyPlayed);
} /// <summary>
/// Play background music
/// </summary>
/// <param name="clip">The audio clip to play</param>
/// <param name="volume"> The volume the music will have</param>
/// <param name="loop">Wether the music is looped</param>
/// <param name="persist"> Whether the audio persists in between scene changes</param>
/// <param name="fadeInSeconds">How many seconds it needs for the audio to fade in/ reach target volume (if higher than current)</param>
/// <param name="fadeOutSeconds"> How many seconds it needs for the audio to fade out/ reach target volume (if lower than current)</param>
/// <param name="onCompletelyPlayed">The audio play completed</param>
/// <returns>The ID of the created Audio object</returns>
public static int PlayMusic(AudioClip clip, float volume, bool loop, bool persist, float fadeInSeconds,
float fadeOutSeconds, Action<Audio> onCompletelyPlayed)
{
return PlayMusic(clip, volume, loop, persist, fadeInSeconds, fadeOutSeconds, -1f, null, onCompletelyPlayed);
} /// <summary>
/// Play background music
/// </summary>
/// <param name="clip">The audio clip to play</param>
/// <param name="volume"> The volume the music will have</param>
/// <param name="loop">Wether the music is looped</param>
/// <param name="persist"> Whether the audio persists in between scene changes</param>
/// <param name="fadeInSeconds">How many seconds it needs for the audio to fade in/ reach target volume (if higher than current)</param>
/// <param name="fadeOutSeconds"> How many seconds it needs for the audio to fade out/ reach target volume (if lower than current)</param>
/// <param name="currentMusicfadeOutSeconds"> How many seconds it needs for current music audio to fade out. It will override its own fade out seconds. If -1 is passed, current music will keep its own fade out seconds</param>
/// <param name="sourceTransform">The transform that is the source of the music (will become 3D audio). If 3D audio is not wanted, use null</param>
/// <param name="onCompletelyPlayed">The audio play completed</param>
/// <returns>The ID of the created Audio object</returns>
public static int PlayMusic(AudioClip clip, float volume, bool loop, bool persist, float fadeInSeconds,
float fadeOutSeconds, float currentMusicfadeOutSeconds, Transform sourceTransform, Action<Audio> onCompletelyPlayed)
{
if (clip == null)
{
Debug.LogError("Sound Manager: Audio clip is null, cannot play music", clip);
} if(ignoreDuplicateMusic)
{
List<int> keys = new List<int>(musicAudio.Keys);
foreach (int key in keys)
{
if (musicAudio[key].audioSource.clip == clip)
{
return musicAudio[key].audioID;
}
}
} instance.Init(); // Stop all current music playing
StopAllMusic(currentMusicfadeOutSeconds); // Create the audioSource
//AudioSource audioSource = instance.gameObject.AddComponent<AudioSource>() as AudioSource;
Audio audio = new Audio(Audio.AudioType.Music, clip, loop, persist, volume, fadeInSeconds, fadeOutSeconds,
sourceTransform, onCompletelyPlayed); // Add it to music list
musicAudio.Add(audio.audioID, audio); return audio.audioID;
} /// <summary>
/// Play a sound fx
/// </summary>
/// <param name="clip">The audio clip to play</param>
/// <param name="onCompletelyPlayed">The audio play completed</param>
/// <returns>The ID of the created Audio object</returns>
public static int PlaySound(AudioClip clip, Action<Audio> onCompletelyPlayed)
{
return PlaySound(clip, 1f, false, null, onCompletelyPlayed);
} /// <summary>
/// Play a sound fx
/// </summary>
/// <param name="clip">The audio clip to play</param>
/// <param name="volume"> The volume the music will have</param>
/// <param name="onCompletelyPlayed">The audio play completed</param>
/// <returns>The ID of the created Audio object</returns>
public static int PlaySound(AudioClip clip, float volume, Action<Audio> onCompletelyPlayed)
{
return PlaySound(clip, volume, false, null, onCompletelyPlayed);
} /// <summary>
/// Play a sound fx
/// </summary>
/// <param name="clip">The audio clip to play</param>
/// <param name="loop">Wether the sound is looped</param>
/// <param name="onCompletelyPlayed">The audio play completed</param>
/// <returns>The ID of the created Audio object</returns>
public static int PlaySound(AudioClip clip, bool loop, Action<Audio> onCompletelyPlayed)
{
return PlaySound(clip, 1f, loop, null, onCompletelyPlayed);
} /// <summary>
/// Play a sound fx
/// </summary>
/// <param name="clip">The audio clip to play</param>
/// <param name="volume"> The volume the music will have</param>
/// <param name="loop">Wether the sound is looped</param>
/// <param name="sourceTransform">The transform that is the source of the sound (will become 3D audio). If 3D audio is not wanted, use null</param>
/// <param name="onCompletelyPlayed">The audio play completed</param>
/// <returns>The ID of the created Audio object</returns>
public static int PlaySound(AudioClip clip, float volume, bool loop, Transform sourceTransform, Action<Audio> onCompletelyPlayed)
{
if (clip == null)
{
Debug.LogError("Sound Manager: Audio clip is null, cannot play music", clip);
} if (ignoreDuplicateSounds)
{
List<int> keys = new List<int>(soundsAudio.Keys);
foreach (int key in keys)
{
if (soundsAudio[key].audioSource.clip == clip)
{
return soundsAudio[key].audioID;
}
}
} instance.Init(); // Create the audioSource
//AudioSource audioSource = instance.gameObject.AddComponent<AudioSource>() as AudioSource;
Audio audio = new Audio(Audio.AudioType.Sound, clip, loop, false, volume, 0f, 0f, sourceTransform, onCompletelyPlayed); // Add it to music list
soundsAudio.Add(audio.audioID, audio); return audio.audioID;
} /// <summary>
/// Play a UI sound fx
/// </summary>
/// <param name="clip">The audio clip to play</param>
/// <param name="onCompletelyPlayed">The audio play completed</param>
/// <returns>The ID of the created Audio object</returns>
public static int PlayUISound(AudioClip clip, Action<Audio> onCompletelyPlayed)
{
return PlayUISound(clip, 1f, onCompletelyPlayed);
} /// <summary>
/// Play a UI sound fx
/// </summary>
/// <param name="clip">The audio clip to play</param>
/// <param name="volume"> The volume the music will have</param>
/// <param name="onCompletelyPlayed">The audio play completed</param>
/// <returns>The ID of the created Audio object</returns>
public static int PlayUISound(AudioClip clip, float volume, Action<Audio> onCompletelyPlayed)
{
if (clip == null)
{
Debug.LogError("Sound Manager: Audio clip is null, cannot play music", clip);
} if (ignoreDuplicateUISounds)
{
List<int> keys = new List<int>(UISoundsAudio.Keys);
foreach (int key in keys)
{
if (UISoundsAudio[key].audioSource.clip == clip)
{
return UISoundsAudio[key].audioID;
}
}
} instance.Init(); // Create the audioSource
//AudioSource audioSource = instance.gameObject.AddComponent<AudioSource>() as AudioSource;
Audio audio = new Audio(Audio.AudioType.UISound, clip, false, false, volume, 0f, 0f, null, onCompletelyPlayed); // Add it to music list
UISoundsAudio.Add(audio.audioID, audio); return audio.audioID;
} #endregion #region Stop Functions /// <summary>
/// Stop all audio playing
/// </summary>
public static void StopAll()
{
StopAll(-1f);
} /// <summary>
/// Stop all audio playing
/// </summary>
/// <param name="fadeOutSeconds"> How many seconds it needs for all music audio to fade out. It will override their own fade out seconds. If -1 is passed, all music will keep their own fade out seconds</param>
public static void StopAll(float fadeOutSeconds)
{
StopAllMusic(fadeOutSeconds);
StopAllSounds();
StopAllUISounds();
} /// <summary>
/// Stop all music playing
/// </summary>
public static void StopAllMusic()
{
StopAllMusic(-1f);
} /// <summary>
/// Stop all music playing
/// </summary>
/// <param name="fadeOutSeconds"> How many seconds it needs for all music audio to fade out. It will override their own fade out seconds. If -1 is passed, all music will keep their own fade out seconds</param>
public static void StopAllMusic(float fadeOutSeconds)
{
List<int> keys = new List<int>(musicAudio.Keys);
foreach (int key in keys)
{
Audio audio = musicAudio[key];
if (fadeOutSeconds > )
{
audio.fadeOutSeconds = fadeOutSeconds;
}
audio.Stop();
}
} /// <summary>
/// Stop all sound fx playing
/// </summary>
public static void StopAllSounds()
{
List<int> keys = new List<int>(soundsAudio.Keys);
foreach (int key in keys)
{
Audio audio = soundsAudio[key];
audio.Stop();
}
} /// <summary>
/// Stop all UI sound fx playing
/// </summary>
public static void StopAllUISounds()
{
List<int> keys = new List<int>(UISoundsAudio.Keys);
foreach (int key in keys)
{
Audio audio = UISoundsAudio[key];
audio.Stop();
}
} #endregion #region Pause Functions /// <summary>
/// Pause all audio playing
/// </summary>
public static void PauseAll()
{
PauseAllMusic();
PauseAllSounds();
PauseAllUISounds();
} /// <summary>
/// Pause all music playing
/// </summary>
public static void PauseAllMusic()
{
List<int> keys = new List<int>(musicAudio.Keys);
foreach (int key in keys)
{
Audio audio = musicAudio[key];
audio.Pause();
}
} /// <summary>
/// Pause all sound fx playing
/// </summary>
public static void PauseAllSounds()
{
List<int> keys = new List<int>(soundsAudio.Keys);
foreach (int key in keys)
{
Audio audio = soundsAudio[key];
audio.Pause();
}
} /// <summary>
/// Pause all UI sound fx playing
/// </summary>
public static void PauseAllUISounds()
{
List<int> keys = new List<int>(UISoundsAudio.Keys);
foreach (int key in keys)
{
Audio audio = UISoundsAudio[key];
audio.Pause();
}
} #endregion #region Resume Functions /// <summary>
/// Resume all audio playing
/// </summary>
public static void ResumeAll()
{
ResumeAllMusic();
ResumeAllSounds();
ResumeAllUISounds();
} /// <summary>
/// Resume all music playing
/// </summary>
public static void ResumeAllMusic()
{
List<int> keys = new List<int>(musicAudio.Keys);
foreach (int key in keys)
{
Audio audio = musicAudio[key];
audio.Resume();
}
} /// <summary>
/// Resume all sound fx playing
/// </summary>
public static void ResumeAllSounds()
{
List<int> keys = new List<int>(soundsAudio.Keys);
foreach (int key in keys)
{
Audio audio = soundsAudio[key];
audio.Resume();
}
} /// <summary>
/// Resume all UI sound fx playing
/// </summary>
public static void ResumeAllUISounds()
{
List<int> keys = new List<int>(UISoundsAudio.Keys);
foreach (int key in keys)
{
Audio audio = UISoundsAudio[key];
audio.Resume();
}
} #endregion
} public class Audio
{
private static int audioCounter = ;
private float volume;
private float targetVolume;
private float initTargetVolume;
private float tempFadeSeconds;
private float fadeInterpolater;
private float onFadeStartVolume;
private AudioType audioType;
private AudioClip initClip;
private Transform sourceTransform; /// <summary>
/// The ID of the Audio
/// </summary>
public int audioID { get; private set; } /// <summary>
/// The audio source that is responsible for this audio
/// </summary>
public AudioSource audioSource { get; private set; } /// <summary>
/// Audio clip to play/is playing
/// </summary>
public AudioClip clip
{
get
{
return audioSource == null ? initClip : audioSource.clip;
}
} /// <summary>
/// Whether the audio will be lopped
/// </summary>
public bool loop { get; set; } /// <summary>
/// Whether the audio persists in between scene changes
/// </summary>
public bool persist { get; set; } /// <summary>
/// How many seconds it needs for the audio to fade in/ reach target volume (if higher than current)
/// </summary>
public float fadeInSeconds { get; set; } /// <summary>
/// How many seconds it needs for the audio to fade out/ reach target volume (if lower than current)
/// </summary>
public float fadeOutSeconds { get; set; } /// <summary>
/// Whether the audio is currently playing
/// </summary>
public bool playing { get; set; } /// <summary>
/// Whether the audio is paused
/// </summary>
public bool paused { get; private set; } /// <summary>
/// Whether the audio is stopping
/// </summary>
public bool stopping { get; private set; } /// <summary>
/// Whether the audio is created and updated at least once.
/// </summary>
public bool activated { get; private set; } /// <summary>
/// The audio played completed.
/// </summary>
public Action<Audio> onComletelyPlayed; public enum AudioType
{
Music,
Sound,
UISound
} public Audio(AudioType audioType, AudioClip clip, bool loop, bool persist, float volume, float fadeInValue,
float fadeOutValue, Transform sourceTransform, Action<Audio> onComletelyPlayed)
{
if (sourceTransform == null)
{
this.sourceTransform = SoundManager.gameobject.transform;
}
else
{
this.sourceTransform = sourceTransform;
} this.audioID = audioCounter;
audioCounter++; this.audioType = audioType;
this.initClip = clip;
this.loop = loop;
this.persist = persist;
this.targetVolume = volume;
this.initTargetVolume = volume;
this.tempFadeSeconds = -;
this.volume = 0f;
this.fadeInSeconds = fadeInValue;
this.fadeOutSeconds = fadeOutValue;
this.onComletelyPlayed = onComletelyPlayed; this.playing = false;
this.paused = false;
this.activated = false; CreateAudiosource(clip, loop);
Play();
} void CreateAudiosource(AudioClip clip, bool loop)
{
audioSource = sourceTransform.gameObject.AddComponent<AudioSource>() as AudioSource; audioSource.clip = clip;
audioSource.loop = loop;
audioSource.volume = 0f;
if (sourceTransform != SoundManager.gameobject.transform)
{
audioSource.spatialBlend = ;
}
} /// <summary>
/// Start playing audio clip from the beggining
/// </summary>
public void Play()
{
Play(initTargetVolume);
} /// <summary>
/// Start playing audio clip from the beggining
/// </summary>
/// <param name="volume">The target volume</param>
public void Play(float volume)
{
if(audioSource == null)
{
CreateAudiosource(initClip, loop);
} audioSource.Play();
playing = true; fadeInterpolater = 0f;
onFadeStartVolume = this.volume;
targetVolume = volume;
} /// <summary>
/// Stop playing audio clip
/// </summary>
public void Stop()
{
fadeInterpolater = 0f;
onFadeStartVolume = volume;
targetVolume = 0f; stopping = true;
} /// <summary>
/// Pause playing audio clip
/// </summary>
public void Pause()
{
audioSource.Pause();
paused = true;
} /// <summary>
/// Resume playing audio clip
/// </summary>
public void Resume()
{
audioSource.UnPause();
paused = false;
} /// <summary>
/// Sets the audio volume
/// </summary>
/// <param name="volume">The target volume</param>
public void SetVolume(float volume)
{
if(volume > targetVolume)
{
SetVolume(volume, fadeOutSeconds);
}
else
{
SetVolume(volume, fadeInSeconds);
}
} /// <summary>
/// Sets the audio volume
/// </summary>
/// <param name="volume">The target volume</param>
/// <param name="fadeSeconds">How many seconds it needs for the audio to fade in/out to reach target volume. If passed, it will override the Audio's fade in/out seconds, but only for this transition</param>
public void SetVolume(float volume, float fadeSeconds)
{
SetVolume(volume, fadeSeconds, this.volume);
} /// <summary>
/// Sets the audio volume
/// </summary>
/// <param name="volume">The target volume</param>
/// <param name="fadeSeconds">How many seconds it needs for the audio to fade in/out to reach target volume. If passed, it will override the Audio's fade in/out seconds, but only for this transition</param>
/// <param name="startVolume">Immediately set the volume to this value before beginning the fade. If not passed, the Audio will start fading from the current volume towards the target volume</param>
public void SetVolume(float volume, float fadeSeconds, float startVolume)
{
targetVolume = Mathf.Clamp01(volume);
fadeInterpolater = ;
onFadeStartVolume = startVolume;
tempFadeSeconds = fadeSeconds;
} /// <summary>
/// Sets the Audio 3D max distance
/// </summary>
/// <param name="max">the max distance</param>
public void Set3DMaxDistance(float max)
{
audioSource.maxDistance = max;
} /// <summary>
/// Sets the Audio 3D min distance
/// </summary>
/// <param name="max">the min distance</param>
public void Set3DMinDistance(float min)
{
audioSource.minDistance = min;
} /// <summary>
/// Sets the Audio 3D distances
/// </summary>
/// <param name="min">the min distance</param>
/// <param name="max">the max distance</param>
public void Set3DDistances(float min, float max)
{
Set3DMinDistance(min);
Set3DMaxDistance(max);
} public void Update()
{
if(audioSource == null)
{
return;
} activated = true; if (volume != targetVolume)
{
float fadeValue;
fadeInterpolater += Time.deltaTime;
if (volume > targetVolume)
{
fadeValue = tempFadeSeconds != -? tempFadeSeconds: fadeOutSeconds;
}
else
{
fadeValue = tempFadeSeconds != - ? tempFadeSeconds : fadeInSeconds;
} volume = Mathf.Lerp(onFadeStartVolume, targetVolume, fadeInterpolater / fadeValue);
}
else if(tempFadeSeconds != -)
{
tempFadeSeconds = -;
} switch (audioType)
{
case AudioType.Music:
{
audioSource.volume = volume * SoundManager.globalMusicVolume * SoundManager.globalVolume;
break;
}
case AudioType.Sound:
{
audioSource.volume = volume * SoundManager.globalSoundsVolume * SoundManager.globalVolume;
break;
}
case AudioType.UISound:
{
audioSource.volume = volume * SoundManager.globalUISoundsVolume * SoundManager.globalVolume;
break;
}
} if (volume == 0f && stopping)
{
audioSource.Stop();
stopping = false;
playing = false;
paused = false;
} // Update playing status
if (audioSource.isPlaying != playing)
{
playing = audioSource.isPlaying;
}
}
}
}
ZSAudioController
 using System;
using System.Collections.Generic;
using UnityEngine;
using ZStudio.SoundManager;
using Object = UnityEngine.Object; public class ZSAudioControllerStub : MonoBehaviour
{
public List<AudioSett> audioSetts;
public AudioGlobalSett audioGlobalSett = new AudioGlobalSett(); public AudioSett GetAudio(string an)
{
return audioSetts.Find(aud => aud.name == an);
}
} [Serializable]
public class AudioGlobalSett
{
public float uiVolome;
public float fxVolume;
public float soundVolume; public bool ignoreDuplicateMusic;
public bool ignoreDuplicateSounds;
public bool ignoreDuplicateUISounds; public AudioGlobalSett()
{
uiVolome = ;
fxVolume = ;
soundVolume = ; ignoreDuplicateMusic = false;
ignoreDuplicateSounds = false;
ignoreDuplicateUISounds = false;
}
} [Serializable]
public class AudioSett
{
public Audio.AudioType type; public string name;
public AudioClip clip;
public float volume;
public bool loop;
public bool persist;
public float fadeInSec;
public float fadeOutSec; public AudioSett()
{
volume = ;
loop = false;
persist = false;
fadeInSec = ;
fadeOutSec = ;
}
} public class ZSAudioController : Singleton<ZSAudioController>
{
private static ZSAudioControllerStub stub; public enum RangeType
{
Music,
Sound,
UISound,
All
} private static void InitStub()
{
var stubs = Object.FindObjectsOfType<ZSAudioControllerStub>();
if (stubs.Length > )
{
Debug.LogWarning("More than one ZSAudioControllerStub in scene.");
foreach (var st in stubs)
{
Object.DestroyObject(st.gameObject);
}
}
else if (stubs.Length == ) stub = stubs[]; if (stub == null)
stub = Object.Instantiate(Resources.Load<ZSAudioControllerStub>("AudioController"));
Object.DontDestroyOnLoad(stub.gameObject);
} public static void Play(string audid, Action<Audio> onPlayed = null)
{
if (stub == null) InitStub(); AudioSett _ass = stub.GetAudio(audid);
if (_ass != null)
{
if (_ass.type == Audio.AudioType.Music)
{
SoundManager.PlayMusic(_ass.clip, _ass.volume, _ass.loop, _ass.persist, _ass.fadeInSec,
_ass.fadeOutSec, onPlayed);
}
else if (_ass.type == Audio.AudioType.Sound)
{
SoundManager.PlaySound(_ass.clip, _ass.volume, _ass.loop, null, onPlayed);
}
else if (_ass.type == Audio.AudioType.UISound)
{
SoundManager.PlayUISound(_ass.clip, _ass.volume, onPlayed);
}
}
} public static void Stop(string audid)
{
if (stub == null) InitStub(); AudioSett _ass = stub.GetAudio(audid);
if (_ass != null)
{
Audio _audio = SoundManager.GetAudio(_ass.clip);
if (_audio != null) _audio.Stop();
}
} public static void Pause(string audid)
{
if (stub == null) InitStub(); AudioSett _ass = stub.GetAudio(audid);
if (_ass != null)
{
Audio _audio = SoundManager.GetAudio(_ass.clip);
if (_audio != null) _audio.Pause();
}
} public static void Resume(string audid)
{
if (stub == null) InitStub(); AudioSett _ass = stub.GetAudio(audid);
if (_ass != null)
{
Audio _audio = SoundManager.GetAudio(_ass.clip);
if (_audio != null) _audio.Resume();
}
} public static void Stop(RangeType range)
{
if (range == RangeType.Music) SoundManager.StopAllMusic();
if (range == RangeType.Sound) SoundManager.StopAllSounds();
if (range == RangeType.UISound) SoundManager.StopAllUISounds();
if (range == RangeType.All) SoundManager.StopAll();
} public static void Pause(RangeType range)
{
if (range == RangeType.Music) SoundManager.PauseAllMusic();
if (range == RangeType.Sound) SoundManager.PauseAllSounds();
if (range == RangeType.UISound) SoundManager.PauseAllUISounds();
if (range == RangeType.All) SoundManager.PauseAll();
} public static void Resume(RangeType range)
{
if (range == RangeType.Music) SoundManager.ResumeAllMusic();
if (range == RangeType.Sound) SoundManager.ResumeAllSounds();
if (range == RangeType.UISound) SoundManager.ResumeAllUISounds();
if (range == RangeType.All) SoundManager.ResumeAll();
}
}
ZSAudioControllerEditor
 using UnityEditor;
using UnityEngine;
using ZStudio.SoundManager; [CustomEditor(typeof(ZSAudioControllerStub))]
[CanEditMultipleObjects]
public class ZSAudioControllerEditor : Editor
{
private SerializedProperty ass;
private SerializedProperty ags;
private Audio.AudioType audioType; private bool showAudio = true;
private bool showGlobal = true;
private int deleteIndex = -;
private int selectedIndex = ; private GUIStyle labelStyle;
private GUIStyle foldoutStyle; // 当对象已启用并处于活动状态时调用此函数
private void OnEnable()
{
ass = serializedObject.FindProperty("audioSetts");
ags = serializedObject.FindProperty("audioGlobalSett");
} private void SetStyles()
{
foldoutStyle = new GUIStyle(EditorStyles.foldout);
Color color = new Color(, , 0.2f);
foldoutStyle.onNormal.background = EditorStyles.boldLabel.onNormal.background;
foldoutStyle.onFocused.background = EditorStyles.boldLabel.onNormal.background;
foldoutStyle.onActive.background = EditorStyles.boldLabel.onNormal.background;
foldoutStyle.onHover.background = EditorStyles.boldLabel.onNormal.background;
foldoutStyle.normal.textColor = color;
foldoutStyle.focused.textColor = color;
foldoutStyle.active.textColor = color;
foldoutStyle.hover.textColor = color;
foldoutStyle.fixedWidth = 1000f; labelStyle = new GUIStyle(EditorStyles.foldout);
color = new Color(, , 0.5f);
labelStyle.onNormal.background = EditorStyles.boldLabel.onNormal.background;
labelStyle.onFocused.background = EditorStyles.boldLabel.onNormal.background;
labelStyle.onActive.background = EditorStyles.boldLabel.onNormal.background;
labelStyle.onHover.background = EditorStyles.boldLabel.onNormal.background;
labelStyle.font = EditorStyles.boldFont;
labelStyle.normal.textColor = color;
labelStyle.focused.textColor = color;
labelStyle.active.textColor = color;
labelStyle.hover.textColor = color;
labelStyle.fixedWidth = 1000f;
} public override void OnInspectorGUI()
{
SetStyles();
serializedObject.Update(); // 全局设定
GlobalSetting(); //GUILayout.Label("添加/删除音乐", foldoutStyle);
EditorGUILayout.Foldout(true, "添加音乐", foldoutStyle);
GUILayout.BeginVertical("Box");
GUILayout.BeginHorizontal("Box");
audioType = (Audio.AudioType) EditorGUILayout.EnumPopup(audioType, GUILayout.MinWidth());
GUILayout.Label("", GUILayout.MaxWidth());
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal("box");
if (GUILayout.Button("Add", GUILayout.Width()))
{
AddAudio(audioType);
}
GUILayout.Label("", GUILayout.MaxWidth());
if (GUILayout.Button("ClearAll", GUILayout.MinWidth()))
{
ass.ClearArray();
}
GUILayout.EndHorizontal();
GUILayout.EndVertical();
GUILayout.Space(); // 移除项
if (deleteIndex > -)
{
RemoveAudio(deleteIndex);
deleteIndex = -;
} showAudio = EditorGUILayout.Foldout(showAudio, new GUIContent("音乐列表"), foldoutStyle);
if (showAudio)
{
PopupAudio();
if (ass.arraySize > selectedIndex)
{
var audio = ass.GetArrayElementAtIndex(selectedIndex);
DrawAudio(audio, selectedIndex);
}
} serializedObject.ApplyModifiedProperties();
} private void GlobalSetting()
{
GUILayout.BeginVertical();
showGlobal = EditorGUILayout.Foldout(showGlobal, "Global Settings", foldoutStyle);
if (showGlobal)
{
var uiv = ags.FindPropertyRelative("uiVolome");
EditorGUILayout.Slider(uiv, , , "UI Volume:");
var fxv = ags.FindPropertyRelative("fxVolume");
EditorGUILayout.Slider(fxv, , , "Fx Volume:");
var sdv = ags.FindPropertyRelative("soundVolume");
EditorGUILayout.Slider(sdv, , , "Sound Volume:");
GUILayout.EndVertical();
}
} private void PopupAudio()
{
string[] names = new string[ass.arraySize];
for (int i = ; i < ass.arraySize; i++)
{
SerializedProperty _ass = ass.GetArrayElementAtIndex(i);
string _name = _ass.FindPropertyRelative("name").stringValue;
names[i] = _name;
} GUILayout.BeginHorizontal(new GUIStyle(EditorStyles.whiteBoldLabel));
selectedIndex = EditorGUILayout.Popup("Audio:", selectedIndex, names);
GUILayout.EndHorizontal();
} private void DrawAudio(SerializedProperty audio, int index)
{
GUILayout.BeginVertical("Box"); GUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Type:", GUILayout.MaxWidth());
SerializedProperty _type = audio.FindPropertyRelative("type");
EditorGUILayout.PropertyField(_type, new GUIContent(""), GUILayout.MaxWidth());
GUILayout.Label("", GUILayout.MaxWidth());
if (GUILayout.Button("-", GUILayout.MaxWidth()))
{
deleteIndex = index;
}
GUILayout.EndHorizontal(); SerializedProperty _clip = audio.FindPropertyRelative("clip");
EditorGUILayout.PropertyField(_clip, new GUIContent("Audio Clip:"));
SerializedProperty _name = audio.FindPropertyRelative("name");
EditorGUILayout.PropertyField(_name, new GUIContent("Audio Name:"));
SerializedProperty _volume = audio.FindPropertyRelative("volume");
EditorGUILayout.Slider(_volume, , , "Volume:");
SerializedProperty _loop = audio.FindPropertyRelative("loop");
EditorGUILayout.PropertyField(_loop, new GUIContent("Loop:"));
SerializedProperty _persist = audio.FindPropertyRelative("persist");
EditorGUILayout.PropertyField(_persist, new GUIContent("Persist:"));
GUILayout.BeginHorizontal();
SerializedProperty _fadeInSec = audio.FindPropertyRelative("fadeInSec");
EditorGUILayout.PropertyField(_fadeInSec, new GUIContent("Fade-In:"));
GUILayout.Label("Sec");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
SerializedProperty _fadeOutSec = audio.FindPropertyRelative("fadeOutSec");
EditorGUILayout.PropertyField(_fadeOutSec, new GUIContent("Fade-Out:"));
GUILayout.Label("Sec");
GUILayout.EndHorizontal(); GUILayout.EndVertical();
} private void AddAudio(Audio.AudioType type)
{
AudioClip[] clips = GetSelectedAudioClips();
for (int i = ; i < clips.Length; i++)
{
ass.arraySize += ;
var _audio = ass.GetArrayElementAtIndex(ass.arraySize - );
_audio.FindPropertyRelative("clip").objectReferenceValue = clips[i];
_audio.FindPropertyRelative("name").stringValue = clips[i].name;
_audio.FindPropertyRelative("type").enumValueIndex = (int)type;
_audio.FindPropertyRelative("volume").floatValue = ;
_audio.FindPropertyRelative("loop").boolValue = false;
_audio.FindPropertyRelative("persist").boolValue = false;
_audio.FindPropertyRelative("fadeInSec").floatValue = ;
_audio.FindPropertyRelative("fadeOutSec").floatValue = ;
}
serializedObject.ApplyModifiedProperties();
} private void RemoveAudio(int index)
{
if (index >= ass.arraySize || index < )
{
Debug.LogWarning("invalid index in DeleteArrayElement: " + index);
}
else
{
ass.DeleteArrayElementAtIndex(index);
// 最后一个元素被删除
if (selectedIndex >= ass.arraySize - )
{
selectedIndex -= ;
if (selectedIndex < ) selectedIndex = ;
}
}
} // 获取选中的音乐或者文件夹下面的音乐
private AudioClip[] GetSelectedAudioClips()
{
var filtered = Selection.GetFiltered<AudioClip>(SelectionMode.DeepAssets);
return filtered;
}
}
  • 测试播放

 // TODEBUG 测试声音播放
ZSAudioController.Play("");

添加音乐只需要在资源视图中选中音乐或者音乐文件夹,点击Add.

Unity3d简便的声音管理方案的更多相关文章

  1. 借鉴redux,实现一个react状态管理方案

    react状态管理方案有很多,其中最简单的最常用的是redux. redux实现 redux做状态管理,是利用reducer和action实现的state的更新. 如果想要用redux,需要几个步骤 ...

  2. C# 程序异常管理方案

    C# 程序异常管理方案 1.程序出现未处理异常(程序中未捕获异常.添加异常处理) 2.程序添加全局异常捕获 tip:程序已处理异常不在捕获范围内. /// <summary> /// 应用 ...

  3. Html5 Egret游戏开发 成语大挑战(九)设置界面和声音管理

    在上一篇中,简单的使用界面元素快速实现了一个游戏中的二级页面,这种直接在游戏页面上做UI的做法并不太好,原因是,UI会让游戏的压力变大,即使它是隐蔽的,如果同样的功能在其它的地方也是一样的,那么就要写 ...

  4. Android之声音管理器《AudioManager》的使用以及音量控制

    以下为网上下载然后拼接-- Android声音管理AudioManager使用 手机都有声音模式,声音.静音还有震动,甚至震动加声音兼备,这些都是手机的基本功能.在Android手机中,我们同样可以通 ...

  5. (转)flutter 新状态管理方案 Provide (一)-使用

    flutter 新状态管理方案 Provide (一)-使用     版权声明:本文为博主原创文章,基于CC4.0协议,首发于https://kikt.top ,同步发于csdn,转载必须注明出处! ...

  6. 关于Unity中的声音管理模块(专题七)

    声音的要素 1: 音频文件AudioClip2: 音源AudioSource;3: 耳朵AudioListener;//全局只能有一个4: 2D/3D音频;//2D只是简单地播放声音,3D可以根据距离 ...

  7. 【云计算】Docker 多进程管理方案

    docker容器内多进程的管理方案 时间 2015-05-08 00:00:00                                               涯余            ...

  8. vuex-- Vue.的中心化状态管理方案(vue 组件之间的通信简化机制)

    vuex-- Vue.的中心化状态管理方案(vue 组件之间的通信简化机制) 如果你在使用 vue.js , 那么我想你可能会对 vue 组件之间的通信感到崩溃 .vuex就是为了解决组件通信问题的. ...

  9. 04、Unity_声音管理器

    1.分享一个Unity中用于管理声音的声音管理器,适合于中小型项目,大项目就算了. 2.借鉴了很多的源码,最后修改完成,吸取百家之长,改为自己所用,哈哈. 3.源码奉上: /* * * 开发时间:20 ...

随机推荐

  1. python线程的条件变量Condition的用法实例

      Condition 对象就是条件变量,它总是与某种锁相关联,可以是外部传入的锁或是系统默认创建的锁.当几个条件变量共享一个锁时,你就应该自己传入一个锁.这个锁不需要你操心,Condition 类会 ...

  2. Android_SQLite简单的增删改查

    SQLite数据库,和其他的SQL数据库不同, 我们并不需要在手机上另外安装一个数据库软件,Android系统已经集成了这个数据库,我们无需像 使用其他数据库软件(Oracle,MSSQL,MySql ...

  3. Codeforces Round #614 (Div. 2) D

    变色失败 只加8分 距离变色只差5分 B题没想到那么简单,结论秒猜,不敢交,傻傻验证5分钟. C题也想了码了好一会儿,我动态维护set做的. 1小时3题,整体难度好像没以前那么大了?(虽然也不强,但比 ...

  4. C# LINQ学习笔记四:LINQ to OBJECT之操作文件目录

    本笔记摘抄自:https://www.cnblogs.com/liqingwen/p/5816051.html,记录一下学习过程以备后续查用. 许多文件系统操作实质上是查询,因此非常适合使用LINQ方 ...

  5. Net项目添加 WebAPI

    1.新建一个  WebApiConfig.cs public static void Register(HttpConfiguration config) { // Web API 配置和服务 // ...

  6. yii2 生成随机字符串

    uuid uuid use Faker\Provider\Uuid; Uuid::uuid(); yii自带 生成32位字符串 Yii::$app->getSecurity()->gene ...

  7. IntelliJ IDEA Ultimate 6.2 版本免费试用期过期后如何破解

    今天早上一打开IntelliJ IDEA时弹出“InteliJ IDEA License Activation”界面,需要激活新的license才可以使用.下面直接使用Activation code进 ...

  8. kanbanflow的使用

    也许在工作中大家都听说过番茄工作法,就是每次在一个番茄钟25分钟内保持高度专注,并且在时间结束的时候会提醒你,然后稍作休息5分钟:此外,在产品迭代开发过程中常常会接受到不同的task:那么,我们是否可 ...

  9. R 常用清洗函数汇总

    目录 1.which() 2.unique() 3.dplyr包 select() filter() arrange() group_by() mutate() transmutate() summa ...

  10. python开发第二篇 :python基础

    python基础a.Python基础      -基础1. 第一句python       -python后缀名可以任意?     -导入模块时如果不是.py文件,以后的文件后缀名是.py.2.两种 ...