public int GetSoundID() { int _instanceID = 0; AudioSource _audioSrc = null; var _enumerator = _audioSrcMap.GetEnumerator(); while (_enumerator.MoveNext()) { var _cur = _enumerator.Current; if (!_cur.Value.isPlaying && _cur.Value.time == 0) { _audioSrc = _cur.Value; _audioSrc.clip = null; break; } } if (null == _audioSrc) { _audioSrc = NewSoundPlayer(); _instanceID = _audioSrc.GetInstanceID(); _audioSrcMap.Add(_instanceID, _audioSrc); } else { _instanceID = _audioSrc.GetInstanceID(); } return(_instanceID); }
void Update() { if (!startedPlaying && Time.time - soundStartTime > SoundStartDelay) { ass.Play(); soundPlayStartTime = Time.time; startedPlaying = true; } if (MuteMusic) { SoundSystem.Instance.MuteMusic = true; } if (startedPlaying && !ass.isPlaying) { SoundSystem.Instance.MuteMusic = false; SoundSystem.Instance.RemoveSound(ass.GetInstanceID()); } else if (startedPlaying && SoundEndDuration > 0f) { if (Time.time - soundPlayStartTime > SoundEndDuration) { SoundSystem.Instance.MuteMusic = false; SoundSystem.Instance.RemoveSound(ass.GetInstanceID()); } } if (startedPlaying && Time.time - soundStartTime > utmostLimit) { SoundSystem.Instance.MuteMusic = false; SoundSystem.Instance.RemoveSound(ass.GetInstanceID()); } }
private Dictionary <int, Part> soundIDToPartIVA = new Dictionary <int, Part>(); //using a separate storage for internal model audio sources as they have completely different reference system public void rebuildCache(AudioSource[] audioSources) { Stopwatch performanceWatch = Stopwatch.StartNew(); soundIDToPart.Clear(); soundIDToPartIVA.Clear(); for (int i = 0; i < audioSources.Length; i++) { AudioSource audioSource = audioSources[i]; for (int p = 0; p < FlightGlobals.ActiveVessel.Parts.Count; p++) { Part part = FlightGlobals.ActiveVessel.Parts[p]; if (part.internalModel && audioSource.transform.IsChildOf(part.internalModel.transform)) { soundIDToPartIVA.Add(audioSource.GetInstanceID(), part); break; } else if (audioSource.transform.IsChildOf(part.transform)) { soundIDToPart.Add(audioSource.GetInstanceID(), part); break; } } } /*foreach (KeyValuePair<int, Part> entry in soundIDToPart) { * UnityEngine.Debug.Log("ENTRY: " + entry.Key + " " + entry.Value.name); * }*/ performanceWatch.Stop(); KSPLog.print("AudioMuffler: VesselSoundsCache rebuild time = " + performanceWatch.ElapsedMilliseconds); }
public async void PlayBgm(string id, float volume = -1f, bool loop = true, bool fadeIn = true) { int hash = Animator.StringToHash(id); if (!bgmMap.ContainsKey(hash)) { throw new Exception($"Can't find bgm with id {id}"); } if (availableBgmAudioSources.Count == 0) { SpawnAdditionalBgmAudioSources(5); } //get values AudioSource source = availableBgmAudioSources.Pop(); AudioClip clip = bgmMap[hash]; float length = clip.length; //set volume if (volume < 0) { source.volume = bgmVolume * masterVolume; } else { source.volume = volume; } //set loop source.loop = loop; //set clip source.clip = clip; source.Play(); currentlyPlayingBgmAudioSources.Add(source.GetInstanceID(), source); if (!loop) { await new WaitForSeconds(length); currentlyPlayingBgmAudioSources.Remove(source.GetInstanceID()); ReturnSourceToPool(true, source); } }
FadingAudioSource(AudioSource source, float fadeDuration, bool fadeIn) { fadingAudioSources.Add(this); sourceToFadingAudioSource.Add(source.GetInstanceID(), this); this.source = source; Reset(fadeDuration, fadeIn); }
public async void PlaySfx(string id, Transform position = null, float volume = -1f, bool loop = false, bool fadeIn = false) { int hash = Animator.StringToHash(id); if (!sfxMap.ContainsKey(hash)) { throw new Exception($"Can't find sfx with id {id}"); } if (availableSfxAudioSources.Count == 0) { SpawnAdditionalSfxAudioSources(5); } //get values AudioSource source = availableSfxAudioSources.Pop(); AudioClip clip = sfxMap[hash]; float length = clip.length; //set volume if (volume < 0) { source.volume = sfxVolume * masterVolume; } else { source.volume = volume; } //set loop source.loop = loop; //set position posCache = position == null ? mainCamera.gameObject.transform.position : position.position; posCache.z = mainCamera.gameObject.transform.position.z; source.gameObject.transform.position = posCache; //set clip source.clip = clip; source.Play(); currentlyPlayingSfxAudioSources.Add(source.GetInstanceID(), source); await new WaitForSeconds(length); currentlyPlayingSfxAudioSources.Remove(source.GetInstanceID()); ReturnSourceToPool(false, source); }
// Sonidos public void MuteSounds() { foreach (AudioSource a in sounds) { if (a.GetInstanceID() != mainMusic.GetInstanceID()) { a.mute = true; } } isSoundsMuted = true; GameParameters.sounds = false; if (affectedSoundsButton != null) { affectedSoundsButton.SetInactiveImage(); } }
public static AudioSource PlayEvent(string path, Transform root = null) { if (Instance == null) { Logger.LogError($"Cannot check if audio path valid as instance == null"); return(null); } if (!IsPathValid(path)) { Logger.LogError($"PlayEvent called with path: \"{path}\" that not valid"); return(null); } var sound = Instance.Sounds[path]; if (root == null) { root = Instance.transform; } var sources = root.gameObject.GetComponents <AudioSource>(); AudioSource source = null; // foreach (var item in sources) // { // if (!item.enabled && !item.isPlaying && item.clip == null) // { // Logger.Log("Found free source"); // source = item; // break; // } // } if (source == null) { Logger.Log("didn't find free source so making one"); source = root.gameObject.AddComponent <AudioSource>(); } source.enabled = true; Instance.CurrentSources.Add(source); var clipAndVolume = sound.GetAudioClip(); source.clip = clipAndVolume.Clip; source.volume = clipAndVolume.Volume; source.outputAudioMixerGroup = Instance.GetGetAudioBus(sound.AudioBus); source.playOnAwake = false; source.loop = sound.LoopClip; source.Play(); Logger.Log($"Playing Audio event: \"{path}\" on source: {source.GetInstanceID()} on gameobject: {source}"); return(source); }
public Pitch(AudioSource target, float endValue, float duration, float delay, bool obeyTimescale, AnimationCurve curve, Tween.LoopType loop, Action startCallback, Action completeCallback) { //set essential properties: SetEssentials(Tween.TweenType.Pitch, target.GetInstanceID(), duration, delay, obeyTimescale, curve, loop, startCallback, completeCallback); //catalog custom properties: _target = target; EndValue = endValue; }
public void PlaySound(AudioSource source, Audio audio, float volume = 1) { if (source == null) { return; } _playedClips[source.GetInstanceID()] = audio.Name; source.PlayOneShot(audio.Clip, volume); }
public void StopSFX(AudioSource source) { for (int i = 0; i < activeSFXAudioSources.Count; i++) { if (activeSFXAudioSources[i].Source.GetInstanceID() == source.GetInstanceID()) { Destroy(source.gameObject); activeSFXAudioSources.RemoveAt(i); return; } } }
public int Play(SoundType sound, int?fadeInTime) { SoundInfo info; if (!_map.TryGetValue(sound, out info)) { Debug.LogError(string.Format("Sound {0} cannot be played. No SoundInfo found", sound.ToString())); return(0); } AudioSource source = _queue.Values.FirstOrDefault(AudioSource => !AudioSource.isPlaying); if (source == null) { Debug.LogError("No available AudioSource"); return(0); } source.loop = info.loop; source.clip = info.clip; if (fadeInTime.HasValue) { int numOfUpdatesRequired = Mathf.RoundToInt((float)fadeInTime.Value / Time.deltaTime); float portionPerUpdate = info.volume / (float)numOfUpdatesRequired; _fadeInQueue.Add(source.GetInstanceID(), new FadeInProps(numOfUpdatesRequired, portionPerUpdate)); source.volume = 0; } else { source.volume = info.volume; } source.Play(); return(source.GetInstanceID()); }
public int PlaySound(SoundTypes st, Vector2?pos = null, bool muteMusic = false, float playDelay = -1f, float endDelay = -1f) { AudioClip clip = GetQuickSound(st); if (clip == null) { return(-1); } GameObject prefab = new GameObject(); prefab.name = "Sound-" + st; AudioSource ass = prefab.AddComponent <AudioSource>(); ass.loop = false; ass.volume = soundVolume; ass.clip = clip; ass.mute = MuteAllSound; prefab.transform.SetParent(soundContainer); if (pos.HasValue) { prefab.transform.position = pos.Value; } else { prefab.transform.position = Vector2.zero; } SoundStopper ss = prefab.AddComponent <SoundStopper>(); ss.MuteMusic = muteMusic; ss.SoundEndDuration = endDelay; ss.SoundStartDelay = playDelay; Sounds.Add(ass.GetInstanceID(), ass); return(ass.GetInstanceID()); }
private void UpdateAudio() { foreach (GameObject obj in GameObject.FindGameObjectsWithTag("Music")) { Debug.Log(obj.transform.parent.name); } music.mute = muteMusic; foreach (AudioSource src in GameObject.FindObjectsOfType <AudioSource>()) { if (src.GetInstanceID() != music.GetInstanceID()) { src.mute = muteSfx; } } }
public int GetSourceID(AudioSource auSo) { if (!(auSo == null)) { int hashcode = auSo.GetInstanceID(); for (int i = 0; i < registeredElements.Count; i++) { if (registeredElements[i].AS.GetInstanceID() == hashcode) { return(registeredElements[i].ID); } } } return(NULL_ID);//not found }
private void Awake() { if (!CREATED) { DontDestroyOnLoad(this.gameObject); CREATED = true; } foreach (SoundInfo info in _sounds) { _map.Add(info.sound, info); } for (int i = 0; i < _audioSourceQueueSize; i++) { AudioSource source = gameObject.AddComponent(typeof(AudioSource)) as AudioSource; _queue.Add(source.GetInstanceID(), source); } }
public static int UnRegisterSource(AudioSource auSo) { if (auSo == null) { return(NULL_ID); } int hasCode = auSo.GetInstanceID(); for (int i = registeredElements.Count - 1; i >= 0; i--) { AudioSourceData asd = registeredElements[i]; if (asd.AS.GetInstanceID() == hasCode) { registeredElements.RemoveAt(i); //ReturnSource(asd, registeredElements, ref countRegElems, i); return(NULL_ID); } } #if UNITY_EDITOR Debug.LogError(typeof(AudioController) + " error: AudioSource not found"); #endif return(NULL_ID); }
private IEnumerator PlaySoundCoroutine(AudioClip clip, float pitch = 1.0f, float stereoPan = 0f, AudioMixerGroup mixerGroup = null, bool noCooldown = false) { if (inactiveAudioSources.Count == 0) { Debug.LogError("Creating new audio source"); CreateNewAudioSource(); } AudioSource selectedAudioSource = inactiveAudioSources[0]; inactiveAudioSources.RemoveAt(0); selectedAudioSource.volume = 1; selectedAudioSource.pitch = pitch; selectedAudioSource.panStereo = stereoPan; selectedAudioSource.outputAudioMixerGroup = GameplayMusicMasterMixer; if (mixerGroup != null) { selectedAudioSource.outputAudioMixerGroup = mixerGroup; } selectedAudioSource.PlayOneShot(clip); #if UNITY_EDITOR if (ClipToDebug.Contains(clip)) { Debug.Log("Played DEBUG SOUND : " + clip + "(" + selectedAudioSource.GetInstanceID() + ")" + " IS BEING PLAYED : " + selectedAudioSource.isPlaying); } #endif activeAudioSources.Add(selectedAudioSource); yield return(new WaitForSeconds(clip.length / pitch)); activeAudioSources.Remove(selectedAudioSource); inactiveAudioSources.Add(selectedAudioSource); }
static bool SourceIsFading(AudioSource source, out FadingAudioSource fas) { return(sourceToFadingAudioSource.TryGetValue(source.GetInstanceID(), out fas)); }
private void LateUpdate() { if (audioSource && run) { // Check play time against previous play time if (audioSource.isPlaying && audioSource.time < prevTime) { restart = true; } // Reinitialize the sample array if the sampleSize is changed if (sample.Length != sampleSize) { sample = new float[sampleSize]; } // AudioSource started playing if (audioSource.isPlaying && (audioSource.isPlaying != prevPlayState || restart)) { #if UNITY_WEBGL && !UNITY_EDITOR WebGL_StartSampling(audioSource.GetInstanceID().ToString(), audioSource.clip.length, sampleSize, dataType.ToString()); #endif prevPlayState = audioSource.isPlaying; restart = false; } // AudioSource is playing if (audioSource.isPlaying) { #if UNITY_WEBGL && !UNITY_EDITOR if (dataType == DataType.Amplitude) { // WebGL_GetAmplitude(audioSource.GetInstanceID().ToString(), sample, sampleSize); WebGL_GetAmplitude(audioSource.GetInstanceID().ToString(), sample, sampleSize); } else // Frequency // WebGL_GetFrequency(audioSource.GetInstanceID().ToString(), sample, sampleSize); { WebGL_GetFrequency(audioSource.GetInstanceID().ToString(), sample); } #else if (dataType == DataType.Amplitude) { audioSource.GetOutputData(sample, 0); } else // Frequency { if (sample.Length == 32) { sample = new float[64]; } AudioListener.GetSpectrumData(sample, 0, FFTWindow.BlackmanHarris); } #endif if (sample != null) { // Average the sample total = 0; for (int i = 0; i < sampleSize; i++) { // Frequency is absolute values only if (dataType == DataType.Frequency) { absoluteValues = true; } // Get the sample value tempVal = sample[i]; // Get the original sign sign = Mathf.Sign(tempVal); if (absoluteValues) // Waveform or Frequency { if (dataType == DataType.Amplitude) { // Get the absolute value tempVal = Mathf.Abs(tempVal); // Add boost tempVal = Mathf.Pow(tempVal, boostBase - boost); // Write boosted value back to the original sample sample[i] = tempVal; } else // Frequency { #if UNITY_WEBGL && !UNITY_EDITOR freqBoost = ScaleRange(boost, 0f, 1f, freqBoostMin, freqBoostMax); freqBoost = freqBoost * -1; tempVal = freqBoost / tempVal; tempVal = Mathf.Clamp(tempVal, 0f, 1f); sample[i] = tempVal; #else // Add boost tempVal = Mathf.Pow(tempVal, boostBase - boost); // Write boosted value back to the original sample sample[i] = tempVal; #endif } } else // Waveform not absolute { // Add boost tempVal = Mathf.Pow(tempVal, boostBase - boost); // Write the boosted and sign corrected value back to the original sample sample[i] = tempVal * sign; } total += sample[i]; } average = total / sampleSize; } else { Debug.Log("sample is null"); } prevTime = audioSource.time; } // AudioSource stopped playing if (!audioSource.isPlaying && audioSource.isPlaying != prevPlayState) { #if UNITY_WEBGL && !UNITY_EDITOR WebGL_StopSampling(audioSource.GetInstanceID().ToString()); #endif // clear values for (int i = 0; i < sampleSize; i++) { sample[i] = 0; } average = 0; prevPlayState = audioSource.isPlaying; prevTime = 0; } } }
private void Start() { //bufferTimeSamplesOffset = ReplayAudioRecorder.Instance.bufferTimeSamples - audioSource.timeSamples; id = audioSource.GetInstanceID(); }
public Part getPartForIVA(AudioSource audioSource) { Part part; return(soundIDToPartIVA.TryGetValue(audioSource.GetInstanceID(), out part) ? part : null); }