本方法是对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.

最新文章

  1. PHP日常开发工具-Sublime应用
  2. 将数据文件从asm移到普通文件系统
  3. android 开发环境
  4. 【leetcode】Best Time to Buy and Sell Stock II
  5. [转]如何根据cpu的processor数来确定程序的并发线程数量
  6. HashMap循环遍历方式及其性能对比
  7. Bootstrap 源码解析
  8. android打成apk
  9. ural1521 War Games 2
  10. 【译文】用Spring Cloud和Docker搭建微服务平台
  11. redis4.0.13主从、哨兵、集群3种模式的 Server端搭建、启动、验证
  12. JAVA之Math类常用数学运算记录
  13. jdbc配置Spring
  14. C# TableLayoutPanel使用方法
  15. mysql外键(FOREIGNKEY)使用介绍
  16. Linux ssh将命令放入后台
  17. BZOJ 2458 最小三角形 | 平面分治
  18. js替换iframe的内容
  19. FireFox新标签页打开搜索和书签
  20. sqlite3 解决并发读写冲突的问题

热门文章

  1. SpringBoot从1.5.1→2.2.4项目加包扫雷三:org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter已过时
  2. JN_0016:查找端口占用
  3. scrapy(一)--Pycharm创建scrapy项目
  4. C# IO流与文件读写学习笔记
  5. win10子系统ubuntu忘记密码解决方案
  6. 剑指offer-面试题23-链表中环的入口节点-双指针
  7. ROS学习--RViz使用的要点
  8. vue中封装jsonp
  9. day03_1spring3
  10. dubbo的服务consumer与provider使用的api版本不一致,是否有影响