public void test() { SoundCategory testCategory = new SoundCategory("Test Category"); SoundGroup testGroup = new SoundGroup("Test Group"); SoundSource testSource = new SoundSource("Test Source"); SoundCategory test2 = new SoundCategory("Test Category 2"); SoundGroup testgroup2 = new SoundGroup("Test Group 2"); SoundSource testsource2 = new SoundSource("Test Source 2"); AudioClip testaudio = (AudioClip)Resources.Load("Jump",typeof(AudioClip)); AudioClip testaudio2 = (AudioClip)Resources.Load("Jump1",typeof(AudioClip)); testSource.setGameObject(GameObject.FindGameObjectWithTag("Dragged")); testSource.addAudioClip(testaudio); testSource.addAudioClip(testaudio2); testgroup2.sources.Add(testsource2); test2.groups.Add(testgroup2); _categories.Add(test2); testGroup.sources.Add(testSource); testCategory.groups.Add(testGroup); _categories.Add(testCategory); }
public void PlaySound(string soundGroupName) { SoundGroup group = Array.Find(soundGroups, item => item.name == soundGroupName); if (group == null) { Debug.LogWarning("Sound Group: " + soundGroupName + " not found!"); return; } group.source.clip = group.GetRandomAudioClip(); group.source.volume = group.volume * (1f + UnityEngine.Random.Range(-group.volumeVariance / 2f, group.volumeVariance / 2f)); group.source.pitch = group.pitch * (1f + UnityEngine.Random.Range(-group.pitchVariance / 2f, group.pitchVariance / 2f)); group.source.Play(); }
/// <summary> /// 增加声音代理辅助器。 /// </summary> /// <param name="soundGroupName">声音组名称。</param> /// <param name="soundAgentHelper">要增加的声音代理辅助器。</param> public void AddSoundAgentHelper(string soundGroupName, ISoundAgentHelper soundAgentHelper) { if (m_SoundHelper == null) { throw new GameFrameworkException("You must set sound helper first."); } SoundGroup soundGroup = (SoundGroup)GetSoundGroup(soundGroupName); if (soundGroup == null) { throw new GameFrameworkException(Utility.Text.Format("Sound group '{0}' is not exist.", soundGroupName)); } soundGroup.AddSoundAgentHelper(m_SoundHelper, soundAgentHelper); }
float GetGroupVolume(SoundGroup group) { if (group == SoundGroup.music) { return(overallVolume * musicVolume); } else if (group == SoundGroup.sound) { return(overallVolume * soundsVolume); } else if (group == SoundGroup.uI) { return(overallVolume * uiVolume); } return(0); }
public void PlayFromSoundGroup(string name) { SoundGroup sg = Array.Find(soundGroups, soundGroup => soundGroup.name == name); if (sg == null) { Debug.LogWarning("Tried to play sound from sound group " + name + " which was not found in AudioManager's sounds array."); return; } int randomIndex = Random.Range(0, sg.sounds.Length); sg.sounds[randomIndex].source.clip = sg.sounds[randomIndex].clip; sg.sounds[randomIndex].source.Play(); }
/// <summary> /// 获取指定声音组。 /// </summary> /// <param name="soundGroupName">声音组名称。</param> /// <returns>要获取的声音组。</returns> public ISoundGroup GetSoundGroup(string soundGroupName) { if (string.IsNullOrEmpty(soundGroupName)) { throw new GameFrameworkException("Sound group name is invalid."); } SoundGroup soundGroup = null; if (m_SoundGroups.TryGetValue(soundGroupName, out soundGroup)) { return(soundGroup); } return(null); }
// ***** SE再生 ***** // SE再生 public void PlaySE(string name, bool loop) { SoundGroup se = null; foreach (SoundGroup sound in SE) { if (sound.soundName.Equals(name)) { se = sound; break; } } if (se == null) { return; } AudioListener.pause = false; // 確認音效是否已在播放 foreach (AudioSource source in SEsources) { if (source.clip == se.audioClip && source.isPlaying) { return; } } // 再生中で無いAudioSouceで鳴らす foreach (AudioSource source in SEsources) { if (false == source.isPlaying) { source.clip = se.audioClip; if (name == "scoreloop") { source.pitch = 2; } else { source.pitch = 1; } source.loop = loop; source.Play(); return; } } }
/// <summary> /// 播放声音。 /// </summary> /// <param name="soundAssetName">声音资源名称。</param> /// <param name="soundGroupName">声音组名称。</param> /// <param name="playSoundParams">播放声音参数。</param> /// <param name="userData">用户自定义数据。</param> /// <returns>声音的序列编号。</returns> public int PlaySound(string soundAssetName, string soundGroupName, PlaySoundParams playSoundParams, object userData) { if (m_ResourceManager == null) { throw new GameFrameworkException("You must set resource manager first."); } if (m_SoundHelper == null) { throw new GameFrameworkException("You must set sound helper first."); } if (playSoundParams == null) { playSoundParams = new PlaySoundParams(); } int serialId = m_Serial++; PlaySoundErrorCode?errorCode = null; string errorMessage = null; SoundGroup soundGroup = GetSoundGroup(soundGroupName) as SoundGroup; if (soundGroup == null) { errorCode = PlaySoundErrorCode.SoundGroupNotExist; errorMessage = string.Format("Sound group '{0}' is not exist.", soundGroupName); } else if (soundGroup.SoundAgentCount <= 0) { errorCode = PlaySoundErrorCode.SoundGroupHasNoAgent; errorMessage = string.Format("Sound group '{0}' is have no sound agent.", soundGroupName); } if (errorCode.HasValue) { if (m_PlaySoundFailureEventHandler != null) { m_PlaySoundFailureEventHandler(this, new PlaySoundFailureEventArgs(serialId, soundAssetName, soundGroupName, playSoundParams, errorCode.Value, errorMessage, userData)); return(serialId); } throw new GameFrameworkException(errorMessage); } m_ResourceManager.LoadAsset(soundAssetName, m_LoadAssetCallbacks, new PlaySoundInfo(serialId, soundGroup, playSoundParams, userData)); return(serialId); }
public void Play(SoundType tp, Vector3 pos) { if (_groups.Any(x => x._type == tp)) { SoundGroup sg = _groups.FirstOrDefault(x => x._type == tp); if (sg._instances.Any(x => !x.isPlaying)) { AudioSource audio = sg._instances.FirstOrDefault(x => !x.isPlaying); audio.transform.position = pos; audio.Play(); } else { PlayNewCash(sg, pos); } } }
public void StopPlaying(string soundName) { SoundGroup sound = Array.Find(soundGroups, item => item.name == soundName); if (sound == null) { Debug.LogWarning("Sound: " + soundName + " not found!"); return; } if (sound.source != null) { sound.source.volume = sound.volume * (1f + UnityEngine.Random.Range(-sound.volumeVariance / 2f, sound.volumeVariance / 2f)); sound.source.pitch = sound.pitch * (1f + UnityEngine.Random.Range(-sound.pitchVariance / 2f, sound.pitchVariance / 2f)); sound.source.Stop(); } }
async protected override void OnNavigatedTo(NavigationEventArgs e) { if (e.Parameter is SoundViewModel ) { soundViewModel = e.Parameter as SoundViewModel; soundGroup = new SoundGroup(); // check if json file is not empty // customMusicGroup = new CustomMusicGroup(); await soundViewModel.GetCustomsounds(); } base.OnNavigatedTo(e); }
public void Play(string soundGroupName, string soundName) { SoundGroup sg = Array.Find(soundGroups, soundGroup => soundGroup.name == soundGroupName); if (sg == null) { Debug.LogWarning("Sound group " + soundGroupName + " not found!"); return; } Sound s = sg.GetSound(soundName); if (s == null) { Debug.LogWarning("Sound " + soundName + " not found!"); return; } s.Play(); }
public void PlayRandFromGroup(string groupName) { //Find Sound Group SoundGroup soundGroup = Array.Find(soundGroups, group => group.name == groupName); //load new clip into source soundGroup.source.clip = soundGroup.GetRandClip(); if (soundGroup != null) { //Play new sound if it exists soundGroup.source.Play(); } else { Debug.Log("Group of name:" + groupName + " was not found"); } }
public void SetSoundLoop(string soundGroupName, string soundName, bool loop) { SoundGroup sg = Array.Find(soundGroups, soundGroup => soundGroup.name == soundGroupName); if (sg == null) { Debug.LogWarning("Sound group " + soundGroupName + " not found!"); return; } Sound s = sg.GetSound(soundName); if (s == null) { Debug.LogWarning("Sound " + soundName + " not found!"); return; } s.loop = loop; }
/// <summary> /// Stops a sound from playing /// </summary> /// <param name="soundName">The name of the sound</param> public void StopSound(string soundGroupName, string soundName) { SoundGroup group = null; if (soundGroupDictionary.TryGetValue(soundGroupName, out group)) { Sound sound = group.GetSound(soundName); if (sound == null) { Debug.LogError("Error: Sound could not be stopped. Sound not found."); return; } sound.audioSource.Stop(); } else { Debug.LogError("Error: Sound could not be stopped. SoundGroup not found."); } }
/// <summary> /// Play the SoundGroup prefab in specific position /// </summary> /// <param name="sndGroup">SoundGroup Prefab</param> /// <param name="pos"></param> /// <returns></returns> public static SoundGroup Play(SoundGroup sndGroup, Vector3 pos) { //If there is no sndGroup Prefab return null; if (sndGroup == null) { return(null); } //Attempt to spawn the soundgroup from the pool at the position and set it to the local variable thisSound SoundGroup thisSound = SpawnSoundGroup(sndGroup, pos); //If something goes wrong and we don't spawn anything if (thisSound == null) { return(null); } //If the sound we spawned is a music if (thisSound.Music) { //Stops and recycles the music that was currently playing if there is one. if (instance.currentMusic) { instance.currentMusic.ForceStop(); } //Set the current music to be our newly spawned music instance.currentMusic = thisSound; //Name it appropriately thisSound.name = "_Music_" + sndGroup.name; } else { //Name it appropriately thisSound.name = "_SFX_" + sndGroup.name; } //Set the soundgroup identifier to be the prefab name. thisSound.identifier = sndGroup.name; //Return our newly spawned soundgroup. return(thisSound); }
public void SetRock(int rock) { currentRock = rock; if (rock == -1) { currentGroup = null; } if (rock == 0) { currentGroup = drums; } if (rock == 1) { currentGroup = rhythm; } if (rock == 2) { currentGroup = leads; } }
/* ----------------------- Stop() ----------------------- */ public void Stop() { // overrides everything state = FadeState.Null: StopAllCoroutines(): if ( audioSource != null ) { audioSource.Stop(): } if ( onFinished != null ) { onFinished(): onFinished = null: } if ( onFinishedObject != null ) { onFinishedObject( onFinishedParam ): onFinishedObject = null: } if ( playingSoundGroup != null ) { playingSoundGroup.DecrementPlayCount(): playingSoundGroup = null: } }
/// <summary> /// 初始化声音代理的新实例。 /// </summary> /// <param name="soundGroup">所在的声音组。</param> public void Init(SoundGroup soundGroup) { if (soundGroup == null) { throw new Exception("Sound group is invalid."); } m_AudioSource = gameObject.GetOrAddComponent <AudioSource>(); m_AudioSource.playOnAwake = false; m_AudioSource.rolloffMode = AudioRolloffMode.Custom; m_CachedTransform = transform; if (soundGroup.MixerGroup != null) { m_AudioSource.outputAudioMixerGroup = soundGroup.MixerGroup; } m_SoundGroup = soundGroup; m_SerialId = 0; m_SoundAsset = null; Reset(); }
public void PlaySoundAtPosition(string soundGroupName, Vector3 position) { SoundGroup group = Array.Find(soundGroups, item => item.name == soundGroupName); if (group == null) { Debug.LogWarning("Sound Group: " + soundGroupName + " not found!"); return; } group.source.volume = group.volume * (1f + UnityEngine.Random.Range(-group.volumeVariance / 2f, group.volumeVariance / 2f)); group.source.minDistance = group.minimunDistance; AudioSource source = positionalSources.Dequeue(); source.pitch = group.pitch * (1f + UnityEngine.Random.Range(-group.pitchVariance / 2f, group.pitchVariance / 2f)); source.transform.position = position; source.clip = group.GetRandomAudioClip(); source.Play(); positionalSources.Enqueue(source); }
/// <summary> /// Play a sound /// </summary> /// <param name="soundName">The name of the sound</param> /// <param name="loop">Whether to loop the sound (optional)</param> /// <param name="volume">The volume of the sound (optional)</param> /// <param name="pitch">The pitch of the sound (optional)</param> public void PlaySound(string soundGroupName, int soundIndex, bool loop = false, float volume = 1, float pitch = 1) { SoundGroup group = null; if (soundGroupDictionary.TryGetValue(soundGroupName, out group)) { Sound sound = group.GetSounds()[soundIndex]; if (sound == null) { Debug.LogError("Error: Sound could not be played. Sound not found."); return; } sound.audioSource.loop = loop; sound.audioSource.volume = volume; sound.audioSource.pitch = pitch; sound.audioSource.Play(); } else { Debug.LogError("Error: Sound could not be played. SoundGroup not found."); } }
private void Delete_Click(object sender, System.Windows.RoutedEventArgs e) { SoundData data = (sender as MenuItem).DataContext as SoundData; SoundGroup group = null; string dataFromAppSettings; if (IsolatedStorageSettings.ApplicationSettings.TryGetValue(Constants.CustomSoundKey, out dataFromAppSettings)) { group = JsonConvert.DeserializeObject <SoundGroup>(dataFromAppSettings); } foreach (var item in group.Items) { if (data.Title.Equals(item.Title)) { group.Items.Remove(item); App.ViewModel.CustomSounds.Items.Remove(item); // Delete sound file from store using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { if (isoStore.FileExists(item.FilePath)) { isoStore.DeleteFile(item.FilePath); break; } } } } // Update ApplicationSettings var newData = JsonConvert.SerializeObject(group); IsolatedStorageSettings.ApplicationSettings[Constants.CustomSoundKey] = newData; IsolatedStorageSettings.ApplicationSettings.Save(); App.ViewModel.LoadData(); NavigationService.Navigate(new Uri("/NavigationPage.xaml", UriKind.Relative)); }
private void CollectSounds() { Sound2[] componentsInChildren = GetComponentsInChildren <Sound2>(includeInactive: true); sounds = new List <SoundMaster>(); groups = new List <SoundGroup>(); map = new Dictionary <string, SoundMaster>(); foreach (Sound2 sound in componentsInChildren) { SoundGroup soundGroup = null; for (int j = 0; j < groups.Count; j++) { if (groups[j].name == sound.group) { soundGroup = groups[j]; break; } } if (soundGroup == null) { SoundGroup soundGroup2 = new SoundGroup(); soundGroup2.name = sound.group; soundGroup = soundGroup2; groups.Add(soundGroup); } string key = sound.group + ":" + sound.name; if (!map.TryGetValue(key, out SoundMaster value)) { SoundMaster soundMaster = new SoundMaster(); soundMaster.master = sound; soundMaster.manager = this; value = soundMaster; sounds.Add(value); map[key] = value; soundGroup.sounds.Add(value); } value.linked.Add(sound); } }
public void SetGroupEnabled(SoundGroup soundGroup, bool status) { // add key if it doesnt exist if (_groupEnabled.ContainsKey(soundGroup) == false) { _groupEnabled.Add(soundGroup, status); } if (_groupEnabled[soundGroup] == status) { return; } _groupEnabled[soundGroup] = status; // find all the sound types on this group and if they're music, stop or play them foreach (var soundData in _soundMap.Values) { if (soundData._group == soundGroup && soundData._music == true) { var audioSource = _sources[soundGroup].Peek(); // _sources[soundGroup].Dequeue(); if (status) { audioSource.Play(); _musicAudioSource = audioSource; } else { if (audioSource.isPlaying) { audioSource.Stop(); _musicAudioSource = null; } } //_sources[soundGroup].Enqueue(audioSource); } } }
private bool AddSoundGroup(SoundGroupInfo info) { if (HasSoundGroup(info.Name)) { return(false); } SoundGroup soundGroup = (new GameObject(name)).AddComponent <SoundGroup>(); soundGroup.OnAwake(); soundGroup.Name = name; soundGroup.AddWhenDontHaveEnoughSound = info.AddWhenDontHaveEnoughSound; soundGroup.Mute = info.Mute; soundGroup.Volume = info.Volume; soundGroup.gameObject.transform.SetParent(instanceRoot); soundGroup.gameObject.transform.localPosition = Vector3.zero; soundGroup.gameObject.transform.localScale = Vector3.one; soundManager.AddSoundGroup(soundGroup); for (int i = 0; i < info.SoundCount; i++) { AddSound(name + "_" + (i + 1), soundGroup); } return(true); }
//public IEnumerator Init() //{ // ResourceManager.LoadAudioMixer("Sound/Mixer/Main"); // allMixGroup //} public void Play(int soundId) { if (soundId == 0) { return; } SoundTableSetting soundTable = SoundTableSettings.Get(soundId); if (soundTable == null) { Debug.LogError("soundtable doesn't exist id = " + soundId); return; } SoundGroup soundGroup = dicSoundGroups[soundTable.Group]; if (soundGroup == null) { Debug.LogError("soundGroup [" + soundTable.Group + "] doesn't exist!id = " + soundId); return; } if (soundGroup.Name == VOICE_GROUP_KEY) { if (currentVoice == 0) { currentVoice = soundId; LoadSoundAssetAndPlay(soundId); } else { queueVoice.Clear(); queueVoice.Enqueue(soundId); } return; } LoadSoundAssetAndPlay(soundId); }
public SaveSoundGroup(SoundGroup data) : base(data) { this.Title = data.Title; }
public bool Equals(SoundGroup other) { return other._fmodGroup == _fmodGroup; }
protected override void UpdateAttacks() { while (m_hitManager.HasAttack) { var atk = m_hitManager.PullAttack; // If the attack can be jump-cancelled after hitting: // Add an on-connect call back to the attack that will // return CanJump to true if the attack wasn't blocked if (atk.kData.JumpCancelOnHit) { atk.onConnect += (obj, args) => { if (!args.kBlocked) this.SoftStun = true; }; } atk.Connect (this.gameObject); stunTimer = (int) atk.kData.Hitstun + 1; Vector2 scaler = Vector2.up + (face == Facing.Right ? Vector2.right : Vector2.left); m_rigid.velocity = Vector2.Scale (atk.TotalLaunch, scaler); if (atk.TotalDamage > 0) { hitFlag = true; m_health -= atk.TotalDamage; } contactSounds = atk.kData.ContactSounds; m_healthbar.SetHealth ((float) m_health / m_maxHealth); } }
/// <summary> /// Play the SoundGroup prefab in specific position /// </summary> /// <param name="sndGroup">SoundGroup Prefab</param> /// <param name="pos"></param> /// <returns></returns> public static SoundGroup Play(SoundGroup sndGroup, Vector3 pos) { //If there is no sndGroup Prefab return null; if (sndGroup == null) return null; //Attempt to spawn the soundgroup from the pool at the position and set it to the local variable thisSound SoundGroup thisSound = SpawnSoundGroup(sndGroup, pos); //If something goes wrong and we don't spawn anything if (thisSound == null) return null; //If the sound we spawned is a music if (thisSound.Music) { //Stops and recycles the music that was currently playing if there is one. if (instance.currentMusic) instance.currentMusic.ForceStop(); //Set the current music to be our newly spawned music instance.currentMusic = thisSound; //Name it appropriately thisSound.name = "_Music_" + sndGroup.name; } else { //Name it appropriately thisSound.name = "_SFX_" + sndGroup.name; } //Set the soundgroup identifier to be the prefab name. thisSound.identifier = sndGroup.name; //Return our newly spawned soundgroup. return thisSound; }
public void Play(string sndName, Vector3 pos) { if(NoSound) return; if(sndName==null) return; if(sndName.Length<1) return; SoundGroup SndToPlay = null; if (items.TryGetValue(sndName, out SndToPlay)) { SoundGroup thisSound = SndToPlay.Spawn(pos); if(thisSound.Music) { currentMusic=thisSound; thisSound.name = "_Music_"+SndToPlay.name; } else { thisSound.name = "_SFX_"+SndToPlay.name; } } else { Debug.Log("SoundManagerGroup "+sndName+" was not found"); } }
private ValidateCustomSoundResponse ValidateCustomSound(SoundData customSound) { var response = new ValidateCustomSoundResponse { IsValid = true, Message = SoundValidation.ValidSoundMessage }; #region Custom sound name validation - Empty string if (customSound.Title.Trim().Length == 0) { response.IsValid = false; response.Message = SoundValidation.EmptySoundMessage; return(response); } #endregion #region Custom sound name validation - Length if (customSound.Title.Length > 10) { response.IsValid = false; response.Message = SoundValidation.InvalidLengthSoundMessage; return(response); } #endregion #region Special character handling in Sound Title foreach (char c in customSound.Title) { if (Char.IsWhiteSpace(c)) { continue; } else if (!Char.IsLetterOrDigit(c)) { response.IsValid = false; response.Message = SoundValidation.SpecialCharacterSoundMessage; return(response); } } #endregion #region Check for duplicate sound SoundGroup group = null; string dataFromAppSettings; if (IsolatedStorageSettings.ApplicationSettings.TryGetValue(Constants.CustomSoundKey, out dataFromAppSettings)) { group = JsonConvert.DeserializeObject <SoundGroup>(dataFromAppSettings); } if (group != null) { foreach (var item in group.Items) { if (customSound.Title.Equals(item.Title)) { response.IsValid = false; response.Message = SoundValidation.DuplicateCustomSoundMessage; return(response); } } } #endregion #region Check for available space in store using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { if (tempFile.Length > isoStore.AvailableFreeSpace) { response.IsValid = false; response.Message = SoundValidation.StorageErrorSoundMessage; return(response); } } #endregion return(response); }
void SetCash(SoundGroup sg) { GameObject ins = GameObject.Instantiate(sg._original, _selfTransform); sg._instances.Add(ins.GetComponent <AudioSource>()); }
public SoundRequest StartSound(string soundName) { SoundGroup group = library.GetSoundGroupFromName(soundName); if (group == null) { Debug.LogError("Soundgoup '" + soundName + "' not found!"); return(null); } if (group.deadTime > 0 && nextTimeAllowed[group.groupID] > Time.unscaledTime) { return(null); } if (soundPlayersOfGroupCount[group.groupID] >= group.maxSoursesCount) { return(null); } int index = GetVacantAudioSourseIndex(); if (index < 0) { return(null); } SoundRequest request = new SoundRequest(); SoundPlayer soundPlayer; if (group.loop && group.loopMode == SoundLoopMode.Crossfade) { int index2 = GetVacantAudioSourseIndex(); if (index2 < 0) { DeactivateSourse(index); return(null); } if (group.deadTime > 0) { nextTimeAllowed[group.groupID] = Time.unscaledTime + group.deadTime; } soundPlayersOfGroupCount[group.groupID] += 1; soundPlayer = new SoundPlayer(request.ID, group.groupID, sourseKeepers[index], index, sourseKeepers[index2], index2); soundPlayer.interruptible = true; soundPlayer.sourseKeeper.sourse.clip = group.GetClip(); soundPlayer.fadeOutTime = group.fadeOutTime; soundPlayer.sourseKeeper.sourse.loop = false; soundPlayer.secondSourseKeeper.sourse.loop = false; if (group.randomize) { soundPlayer.sourseKeeper.sourse.pitch = 1 + (Random.value - 0.5f) * group.pitchRndValue; soundPlayer.sourseKeeper.SetMultiplier(group.volume * (1 - Random.value * group.volumeRndValue)); } else { soundPlayer.sourseKeeper.sourse.pitch = 1; soundPlayer.sourseKeeper.SetMultiplier(group.volume); } soundPlayer.secondSourseKeeper.sourse.clip = soundPlayer.sourseKeeper.sourse.clip; soundPlayer.secondSourseKeeper.sourse.pitch = soundPlayer.sourseKeeper.sourse.pitch; soundPlayer.secondSourseKeeper.SetMultiplier(soundPlayer.sourseKeeper.VoulumeMultiplier); soundPlayer.duration = soundPlayer.sourseKeeper.sourse.clip.length / soundPlayer.sourseKeeper.sourse.pitch * group.maxLoopCount; soundPlayer.crossFadeLoop = true; soundPlayer.playCoroutine = StartCoroutine(LoopCrossFade(soundPlayer, group.fadeStartTime, group.fadeDuration)); soundPlayersDictionary.Add(request.ID, soundPlayer); } else { if (group.deadTime > 0) { nextTimeAllowed[group.groupID] = Time.unscaledTime + group.deadTime; } soundPlayersOfGroupCount[group.groupID] += 1; soundPlayer = new SoundPlayer(request.ID, group.groupID, sourseKeepers[index], index); soundPlayer.interruptible = group.interruptible; soundPlayer.sourseKeeper.sourse.clip = group.GetClip(); soundPlayer.fadeOutTime = group.fadeOutTime; soundPlayer.sourseKeeper.sourse.loop = group.loop; if (group.randomize) { soundPlayer.sourseKeeper.sourse.pitch = 1 + (Random.value - 0.5f) * group.pitchRndValue; soundPlayer.sourseKeeper.SetMultiplier(group.volume * (1 - Random.value * group.volumeRndValue)); } else { soundPlayer.sourseKeeper.sourse.pitch = 1; soundPlayer.sourseKeeper.SetMultiplier(group.volume); } if (group.loop) { soundPlayer.duration = soundPlayer.sourseKeeper.sourse.clip.length / soundPlayer.sourseKeeper.sourse.pitch * group.maxLoopCount; } else { soundPlayer.duration = soundPlayer.sourseKeeper.sourse.clip.length / soundPlayer.sourseKeeper.sourse.pitch; } soundPlayersDictionary.Add(request.ID, soundPlayer); soundPlayer.playCoroutine = StartCoroutine(AwaitStopRoutine(soundPlayer)); soundPlayer.sourseKeeper.sourse.Play(); } return(request); }
//public SoundGroup m_soundGroup = SoundGroup.Generic; //public Range m_volumeRange = new Range(1f, 1f); // Methods public void Awake() { if(m_audioGroups != null && m_audioGroups.Count>0) m_currentGroup = m_audioGroups[0]; }
/// <summary> /// 播放声音 /// </summary> /// <param name="soundAsset">声音资源</param> /// <param name="soundGroupName">声音组名称。</param> /// <param name="priority">加载声音资源的优先级。</param> /// <param name="playSoundParams">播放声音参数。</param> /// <param name="userData">用户自定义数据。</param> /// <returns>声音的序列编号。</returns> /// <exception cref="GameFrameworkException"></exception> public int PlaySound(object soundAsset, string soundGroupName, int priority, PlaySoundParams playSoundParams, object userData) { if (m_ResourceManager == null) { throw new GameFrameworkException("You must set resource manager first."); } if (m_SoundHelper == null) { throw new GameFrameworkException("You must set sound helper first."); } if (playSoundParams == null) { playSoundParams = new PlaySoundParams(); } int serialId = m_Serial++; PlaySoundErrorCode?errorCode = null; string errorMessage = null; SoundGroup soundGroup = (SoundGroup)GetSoundGroup(soundGroupName); if (soundGroup == null) { errorCode = PlaySoundErrorCode.SoundGroupNotExist; errorMessage = string.Format("Sound group '{0}' is not exist.", soundGroupName); } else if (soundGroup.SoundAgentCount <= 0) { errorCode = PlaySoundErrorCode.SoundGroupHasNoAgent; errorMessage = string.Format("Sound group '{0}' is have no sound agent.", soundGroupName); } if (errorCode.HasValue) { if (m_PlaySoundFailureEventHandler != null) { m_PlaySoundFailureEventHandler(this, new PlaySoundFailureEventArgs(serialId, soundAsset.ToString(), soundGroupName, playSoundParams, errorCode.Value, errorMessage, userData)); return(serialId); } throw new GameFrameworkException(errorMessage); } m_SoundsBeingLoaded.Add(serialId); var playSoundInfo = new PlaySoundInfo(serialId, soundGroup, playSoundParams, userData); var soundAgent = playSoundInfo.SoundGroup.PlaySound(serialId, soundAsset, playSoundParams, out errorCode); if (soundAgent != null) { if (m_PlaySoundSuccessEventHandler != null) { m_PlaySoundSuccessEventHandler(this, new PlaySoundSuccessEventArgs(serialId, soundAsset.ToString(), soundAgent, 0f, userData)); } } else { m_SoundsToReleaseOnLoad.Remove(serialId); m_SoundHelper.ReleaseSoundAsset(soundAsset); errorMessage = string.Format("Sound group '{0}' play sound asset '{1}' failure.", soundGroupName, soundAsset); if (m_PlaySoundFailureEventHandler != null) { m_PlaySoundFailureEventHandler(this, new PlaySoundFailureEventArgs(serialId, soundAsset.ToString(), soundGroupName, playSoundParams, errorCode.Value, errorMessage, userData)); } else { throw new GameFrameworkException(errorMessage); } } return(serialId); }
/// <summary> /// Play the SoundGroup prefab at position 0 /// </summary> /// <param name="sndGroup">SoundGroup Prefab</param> /// <returns></returns> public static SoundGroup Play(SoundGroup sndGroup) { return Play(sndGroup, Vector3.zero); }
/// <summary> /// Adds this Soundgroup prefab to our pool of spawnable prefabs /// </summary> /// <param name="prefab">Soundgroup prefab to add</param> public static void AddToPool(SoundGroup prefab) { if (isShuttingDown) return; // If the prefab isn't null and it doesn't exist on our dictionary yet, add it. if (prefab != null && !instance.pooledObjects.ContainsKey(prefab)) { var list = new List<SoundGroup>(); instance.pooledObjects.Add(prefab, list); } }
/// <summary> /// Send the soundgroup object back to the pool to be reused later. /// </summary> /// <param name="obj">Soundgroup object to recycle</param> public static void RecycleSoundToPool(SoundGroup obj) { if (isShuttingDown || obj == null) return; //Try and get the prefab reference from the pool dictionary SoundGroup groupPrefab = null; instance.spawnedObjects.TryGetValue(obj, out groupPrefab); //If the prefab couldn't be found if (groupPrefab == null) { //Destroy the object oldschool way, it wasn't pooled :( Destroy(obj.gameObject); return; } //If the object isn't null if (obj != null) { //Add it back to the pool list instance.pooledObjects[groupPrefab].Add(obj); //Remove it from the currently spawned objects list instance.spawnedObjects.Remove(obj); } //Parent the object back to our pool container and hide it obj.transform.SetParent(instance.SoundsPool); obj.gameObject.SetActive(false); }
/// <summary> /// Spawn soundgroup from pool /// </summary> /// <param name="prefab">Desired Prefab to spawn</param> /// <param name="position">Desired spawn position</param> /// <returns></returns> public static SoundGroup SpawnSoundGroup(SoundGroup prefab, Vector3 position) { if (isShuttingDown) return null; List<SoundGroup> list; SoundGroup obj; obj = null; //Get a list from the dictionary with the current objects of this prefab we have on the pool if (instance.pooledObjects.TryGetValue(prefab, out list)) { //While we don't have an object to spawn and our list still has objects in there. while (obj == null && list.Count > 0) { //While we haven't picked one, check if the one at 0 is one we can use. if (list[0] != null) obj = list[0]; //Remove the one at 0. list.RemoveAt(0); } } else { //This prefab is definitely not in the list D: let's add it there for later. AddToPool(prefab); } //If I still don't have an object to spawn, means my pool doesn't have that object, let's instantiate one old-style. if (obj == null) obj = (SoundGroup)Instantiate(prefab); //Set the object's name to be my prefab name. obj.transform.name = prefab.name; //Parent it to the Current Playing Transform obj.transform.SetParent(instance.SoundsPlaying); //Set the position to be the desired position. obj.transform.position = position; //Set it's gameobject to active (if it's coming from the pool it was deactivated) obj.gameObject.SetActive(true); //Add it to the list of currently spawned objects instance.spawnedObjects.Add(obj, prefab); //Return the spawned object. return obj; }
/** * 播放指定的声音.并且可以指定一个控制组. * @param url * @param times 0值播一次.-1无限循环 * @param group * @return 返回一个声音元素. */ public static SoundItem play(string url, bool loop = false, string group = "effect") { SoundGroup lb = getSoundGroup(group); return(lb.play(url, loop)); }
public bool SetCurrentGroup(string groupName) { foreach (SoundGroup group in m_audioGroups) { if (group.groupName == groupName) { m_currentGroup = group; return true; } } return false; }