Exemple #1
0
        static void GetAudioStats(AudioClip ac, ref ObjectStatInfo ret)
        {
            if (ac == null)
            {
                return;
            }

            if (!ret.audio_total.Contains(ac.GetInstanceID()))
            {
                ret.audio_memory += (double)Profiler.GetRuntimeMemorySizeLong(ac);
                ret.audio_total.Add(ac.GetInstanceID());
            }
        }
        public void EnqueueFeedback(AudioClip clip)
        {
            if (clipTimes.ContainsKey(clip.GetInstanceID()))
            {
                return;
            }

            clipTimes.Add(clip.GetInstanceID(), Time.time + spamTimer);

            feedbackQueue.Enqueue(clip);

            if (feedbackCoroutine == null)
            {
                feedbackCoroutine = StartCoroutine(PlayFeedback());
            }
        }
Exemple #3
0
        internal void ExportAudio(AudioClip audio)
        {
            if (audio == null)
            {
                return;
            }
            string path = AssetDatabase.GetAssetPath(audio.GetInstanceID());

            if (exportedAudio.Contains(path))
            {
                return;
            }

            exportedAudio.Add(path);
            string dest = Path.Combine(AudioDir, Path.GetFileName(path));

            try
            {
                File.Copy(path, dest, true);
            }
            catch (UnityException ue)
            {
                Debug.Log(ue.ToString());
                throw;
            }
        }
Exemple #4
0
 public static void PlayEffect(AudioClip clip, AudioMixerGroup mixer = null, Transform t = null, float volume = 1, float pitch = 1, float pan = 0, float spatialBlend = 0, float minDist = 1, float maxDist = 100)
 {
         #if UNITY_EDITOR
     if (!Application.isPlaying)
     {
         return;
     }
         #endif
     if (clip == null)
     {
         return;
     }
     int id = clip.GetInstanceID();
     if (instance.lastPlayed.ContainsKey(id) &&
         Time.time - instance.lastPlayed[id] < instance.minPlayInterval)
     {
         return;
     }
     instance.lastPlayed[id] = Time.time;
     AudioSource source = instance.sfxSources[instance.currentSFXSource];
     if (t != null)
     {
         source.gameObject.transform.position = t.position;
     }
     source.pitch                 = pitch;
     source.clip                  = clip;
     source.volume                = volume;
     source.spatialBlend          = spatialBlend;
     source.panStereo             = pan;
     source.minDistance           = minDist;
     source.maxDistance           = maxDist;
     source.outputAudioMixerGroup = mixer;
     source.Play();
     instance.currentSFXSource = (instance.currentSFXSource + 1) % instance.sfxSourcesCount;
 }
    public override Hashtable EditorDragDrop(object o)
    {
        if (typeof(AudioClip).IsAssignableFrom(o.GetType()))
        {
            AudioClip ac = (AudioClip)o;

            string path = UnityEditor.AssetDatabase.GetAssetPath(ac.GetInstanceID( ));

            int index = path.IndexOf("Resources/");

            if (index > 0)
            {
                path = path.Substring(index + "Resources/".Length);

                int dot = path.LastIndexOf('.');
                if (dot >= 0)
                {
                    path = path.Substring(0, dot);
                }

                Hashtable hashtable = new Hashtable( );
                hashtable["name"] = path;

                return(hashtable);
            }
        }

        return(null);
    }
 public void ClearAudioClip(ref AudioClip target)
 {
     if (target == null)
     {
         return;
     }
     SetResource(target.GetInstanceID(), null, typeof(AudioClip));
     target = null;
 }
Exemple #7
0
        protected AudioSource GetSFXSouce(AudioClip pClip, int pLimitNumber, bool pLoop)
        {
            try
            {
                if (pLimitNumber > 0 || pLoop)
                {
                    if (!pLoop)
                    {
                        int countSameClips = 0;
                        for (int i = mSFXSources.Length - 1; i >= 0; i--)
                        {
                            if (mSFXSources[i].isPlaying && mSFXSources[i].clip != null && mSFXSources[i].clip.GetInstanceID() == pClip.GetInstanceID())
                            {
                                countSameClips++;
                            }
                            else if (!mSFXSources[i].isPlaying)
                            {
                                mSFXSources[i].clip = null;
                            }
                        }
                        if (countSameClips < pLimitNumber)
                        {
                            for (int i = mSFXSources.Length - 1; i >= 0; i--)
                            {
                                if (mSFXSources[i].clip == null)
                                {
                                    return(mSFXSources[i]);
                                }
                            }

                            return(CreateMoreSFXSource());
                        }
                    }
                    else
                    {
                        for (int i = mSFXSources.Length - 1; i >= 0; i--)
                        {
                            if (mSFXSources[i].clip == null || !mSFXSources[i].isPlaying ||
                                mSFXSources[i].clip.GetInstanceID() == pClip.GetInstanceID())
                            {
                                return(mSFXSources[i]);
                            }
                        }
                    }
                }
                else
                {
                    return(mSFXSourceUnlimited);
                }
                return(null);
            }
            catch (Exception ex)
            {
                Debug.LogError(ex.ToString());
                return(null);
            }
        }
Exemple #8
0
        public void ExportAudio(AudioClip asset)
        {
            string assetPath  = AssetDatabase.GetAssetPath(asset.GetInstanceID());
            string exportPath = Path.Combine(Path.Combine(assets.AudioDir, ".."), assetPath.Replace("Assets/", ""));

            if (!Directory.Exists(Path.GetDirectoryName(exportPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(exportPath));
            }
            File.Copy(assetPath, exportPath, true);
            //Debug.Log("Exported Audio asset to " + exportPath);
        }
 private void PlayAudio(AudioClip clip)
 {
     if (clip.GetInstanceID() == backgroundAudio.GetInstanceID())
     {
         transform.GetChild(0).GetComponent <AudioSource>().volume = 0.05f;
     }
     else
     {
         transform.GetChild(0).GetComponent <AudioSource>().volume = 1f;
     }
     transform.GetChild(0).GetComponent <AudioSource>().clip = clip;
     transform.GetChild(0).GetComponent <AudioSource>().Play();
 }
Exemple #10
0
        public void AddLowFlyBySound(SoundCollection collection, AudioClip clip)
        {
            var sample = EntityManager.CreateEntity();

            AddClip(clip);
            EntityManager.AddComponentData(sample, new SharedAudioClip {
                ClipInstanceID = clip.GetInstanceID()
            });
            m_SampleFlyByEntities.Add(new SampleInfo {
                Length = clip.length, PlayerEntity = sample, Intensity = 0
            });
            m_SampleLowFreeList.Add(m_SampleFlyByEntities.Length - 1);
        }
Exemple #11
0
        public void AddDistributedSamplePlayback(AudioClip clip)
        {
            var sample = EntityManager.CreateEntity();

            AddClip(clip);
            EntityManager.AddComponentData(sample, new AdditiveState());
            EntityManager.AddComponentData(sample, new SamplePlayback {
                Volume = 1, Loop = 1, Pitch = 1
            });
            EntityManager.AddComponentData(sample, new SharedAudioClip {
                ClipInstanceID = clip.GetInstanceID()
            });
            m_SampleEntities.Add(sample);
        }
 public bool LoadAudioClip(ref AudioClip target, string fileName)
 {
     if (string.IsNullOrEmpty(fileName))
     {
         return(false);
     }
     ClearAudioClip(ref target);
     target = ResourceMgr.Instance.LoadAudioClip(fileName, ResourceCacheType.rctRefAdd);
     if (target != null)
     {
         SetResource(target.GetInstanceID(), target, typeof(AudioClip));
     }
     return(target != null);
 }
Exemple #13
0
        public Dictionary <int, AudioDetails> GetNewObjectInstanceIdList(IEnumerable <AudioClip> scanedAllObject)
        {
            Dictionary <int, AudioDetails> returnValues = new Dictionary <int, AudioDetails>();

            foreach (var newItem in scanedAllObject)
            {
                AudioClip    tAudio       = newItem as AudioClip;
                AudioDetails tMeshDetails = new AudioDetails();

                tMeshDetails.objectName = tAudio.name;


                returnValues.Add(tAudio.GetInstanceID(), tMeshDetails);
            }
            return(returnValues);
        }
Exemple #14
0
    private bool CheckRepeatLimit(ref AudioClip audioClip)
    {
        int instanceID = audioClip.GetInstanceID();

        if (!this.previousPlayTimes.ContainsKey(instanceID))
        {
            this.previousPlayTimes[instanceID] = Time.realtimeSinceStartup;
            return(true);
        }
        float realtimeSinceStartup = Time.realtimeSinceStartup;

        if (this.previousPlayTimes[instanceID] < realtimeSinceStartup - 0.15f)
        {
            this.previousPlayTimes[instanceID] = realtimeSinceStartup;
            return(true);
        }
        return(false);
    }
        public ImportInfo(AudioClip clip)
        {
            Clip     = clip;
            Path     = AssetDatabase.GetAssetPath(clip.GetInstanceID());
            GUID     = AssetDatabase.AssetPathToGUID(Path);
            Importer = AssetImporter.GetAtPath(Path) as AudioImporter;

            if (GATEditorUtilities.IsInResources(Path))
            {
                PathInResources = GATEditorUtilities.PathInResources(Path);
            }
            else if (GATEditorUtilities.IsInStreamingAssets(Path))
            {
                PathInResources = GATEditorUtilities.PathInStreamingAssets(Path);
                System.IO.Path.ChangeExtension(PathInResources, System.IO.Path.GetExtension(Importer.assetPath));
                IsStreamingAsset = true;
            }
        }
Exemple #16
0
 private AudioClipSubtitle GetSubtitle(AudioClip clip, out Dictionary dictionary)
 {
     if (Dictionaries != null && Dictionaries.Length > 0)
     {
         int instanceID = clip.GetInstanceID();
         foreach (var d in Dictionaries)
         {
             if (d != null)
             {
                 AudioClipSubtitle subtitle = d.GetSubtitle(instanceID);
                 if (subtitle != null)
                 {
                     dictionary = d;
                     return(subtitle);
                 }
             }
         }
     }
     dictionary = null;
     return(null);
 }
        public SoundBase Spawn2D(AudioClip audioClip, float volume = 1f, bool isLooped = false)
        {
            if (_pool == null)
            {
                return(null);
            }

            var soundId = audioClip.GetInstanceID();

            if (PlayingSounds.TryGetValue(soundId, out var instances))
            {
                if (instances.Count >= MaxDuplicateSoundsCount)
                {
                    ReturnInstance(instances[0]);
                }
            }

            var soundBase = _pool.GetInstance();

            var finalVolume = GameSettings.SoundEnabled.Value ? volume * GameSettings.SoundVolume.Value : 0f;

            soundBase.transform.parent = _soundsTransform;

            soundBase.Play(audioClip, finalVolume, isLooped);

            if (PlayingSounds.TryGetValue(soundId, out instances))
            {
                instances.Add(soundBase);
            }
            else
            {
                PlayingSounds.Add(soundId, new CustomList <SoundBase>(MaxDuplicateSoundsCount)
                {
                    soundBase
                });
            }

            return(soundBase);
        }
Exemple #18
0
        public static void PlayEffect(AudioClip clip, Transform t = null, float volume = 1, float pitch = 1)
        {
            int id = clip.GetInstanceID();

            if (instance.lastPlayed.ContainsKey(id) &&
                Time.time - instance.lastPlayed[id] < instance.minPlayInterval)
            {
                return;
            }
            instance.lastPlayed[id] = Time.time;
            AudioSource source = instance.sfxSources[instance.currentSFXSource];

            if (t != null)
            {
                source.gameObject.transform.position = t.position;
            }
            source.pitch  = pitch;
            source.clip   = clip;
            source.volume = volume * instance.sfxVolume;
            source.Play();
            instance.currentSFXSource = (instance.currentSFXSource + 1) % instance.sfxSourcesCount;
        }
        private static void Convert(AudioClip clip)
        {
            string assetPath = AssetDatabase.GetAssetPath(clip.GetInstanceID());
            string newPath   = System.IO.Path.ChangeExtension(assetPath, ".asset");

            //Check if we have a asset here already. If so, do nothing
            if (AssetDatabase.LoadAssetAtPath(newPath, typeof(Ardenfall.ArdenAudioClip)) != null)
            {
                return;
            }

            Ardenfall.ArdenAudioClip clipWrapper = ScriptableObject.CreateInstance <Ardenfall.ArdenAudioClip>();
            clipWrapper.audioClip = clip;

            AssetDatabase.CreateAsset(clipWrapper, newPath);

            clip.hideFlags = HideFlags.HideInHierarchy;
            EditorUtility.SetDirty(clip);

            AssetDatabase.SaveAssets();

            AssetDatabase.Refresh();
        }
Exemple #20
0
    void DrawEntryBoard(Dictionary <string, AudioEntry> dictionary)
    {
        if (dictionary == null)
        {
            return;
        }

        if (displayId != "" && currentAudioEntry == null)
        {
            if (dictionary.TryGetValue(displayId, out currentAudioEntry))
            {
            }
        }

        if (currentAudioEntry == null)
        {
            currentAudioEntry = new AudioEntry( );
        }

        EditorGUILayout.BeginVertical("box", GUILayout.Width(200));

        string key = displayId, path = currentAudioEntry.path;
        int    loadLevel = currentAudioEntry.loadLevel;


        AudioType type = currentAudioEntry.type;

        EditorGUILayout.BeginHorizontal();

        EditorGUILayout.LabelField(new GUIContent("ID:"), GUILayout.Width(50));
        key = EditorGUILayout.TextField(key);

        EditorGUILayout.EndHorizontal();


        EditorGUILayout.BeginHorizontal();

        EditorGUILayout.LabelField(new GUIContent("Path:"), GUILayout.Width(50));

        Color oldColor = GUI.color;

        GUI.color = Color.yellow;
        EditorGUILayout.LabelField(path);

        GUI.color = oldColor;

        EditorGUILayout.EndHorizontal();
        if (GUILayout.Button("Get Asset Path"))
        {
            Object selectedObj = Selection.activeObject;

            if (selectedObj != null)
            {
                AudioClip audioClip = (AudioClip)selectedObj;

                if (audioClip != null)
                {
                    path = AssetDatabase.GetAssetPath(audioClip.GetInstanceID());
                    DebugWrapper.Log(path);
                    string[] pathSplitted = path.Split('/');

                    bool startAdding = false;

                    string fileName = "";

                    for (int splitedIndex = 0; splitedIndex < pathSplitted.Length; splitedIndex++)
                    {
                        if (startAdding)
                        {
                            fileName += pathSplitted [splitedIndex] + "/";
                        }

                        if (pathSplitted [splitedIndex] == "Resources")
                        {
                            startAdding = true;
                        }
                    }

                    string[] fileNameSplited = fileName.Split('.');
                    path = fileNameSplited[0];

                    DebugWrapper.Log(path);
                }
            }
        }

        float inherentVolume = currentAudioEntry.inherentVolume;

        EditorGUILayout.BeginHorizontal();

        EditorGUILayout.LabelField(new GUIContent("Volume:"), GUILayout.Width(50));
        inherentVolume = EditorGUILayout.Slider(inherentVolume, 0.0f, 1.0f);

        EditorGUILayout.EndHorizontal();

        currentAudioEntry.inherentVolume = inherentVolume;


        EditorGUILayout.BeginHorizontal();

        EditorGUILayout.LabelField(new GUIContent("Load Level:"), GUILayout.Width(60));
        loadLevel = EditorGUILayout.IntField(loadLevel, GUILayout.Width(15));

        AudioClipLoadType aclt = currentAudioEntry.loadType;

        EditorGUILayout.Space();

        EditorGUILayout.LabelField(new GUIContent("Type:"), GUILayout.Width(30));

        aclt = (AudioClipLoadType)EditorGUILayout.EnumPopup(aclt, GUILayout.Width(140));

        currentAudioEntry.loadType = aclt;

        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();

        EditorGUILayout.LabelField(new GUIContent("Type:"));

        type = (AudioType)EditorGUILayout.EnumPopup(type, GUILayout.Width(50));

        EditorGUILayout.EndHorizontal();


        EditorGUILayout.EndVertical();

        displayId = key;
        currentAudioEntry.path      = path;
        currentAudioEntry.loadLevel = loadLevel;
        currentAudioEntry.type      = type;
    }
Exemple #21
0
        public void PlayLoop(AudioClip audioClip)
        {
            AudioSource audioSource = AudioManager.Play(audioClip, transform.position, volume, true, audioClip.GetInstanceID().ToString());

            audioSource.pitch = Random.Range(minMaxPitch.min, minMaxPitch.max);
        }
Exemple #22
0
 public AudioClipSubtitle GetSubtitle(AudioClip clip)
 {
     return(GetSubtitle(clip.GetInstanceID()));
 }
Exemple #23
0
 public void StopSFX(AudioClip pClip)
 {
     if (pClip == null)
     {
         return;
     }
     for (int i = 0; i < mSFXSources.Length; i++)
     {
         if (mSFXSources[i].clip != null && mSFXSources[i].clip.GetInstanceID() == pClip.GetInstanceID())
         {
             mSFXSources[i].Stop();
             mSFXSources[i].clip = null;
         }
     }
 }
Exemple #24
0
        protected override JSONObject ExportResource(ExportPreset preset)
        {
            JSONObject audioClipJSON  = base.ExportResource(preset);
            JSONObject dataJSON       = audioClipJSON.GetField("data");
            JSONObject editorInfoJSON = audioClipJSON.GetField("editorInfo");

            if (dataJSON == null)
            {
                dataJSON = new JSONObject(JSONObject.Type.OBJECT);
                audioClipJSON.AddField("data", dataJSON);
            }
            if (editorInfoJSON == null)
            {
                editorInfoJSON = new JSONObject(JSONObject.Type.OBJECT);
                audioClipJSON.AddField("editorInfo", editorInfoJSON);
            }
            editorInfoJSON.AddField("name", audioClip.name);
            dataJSON.AddField("length", audioClip.length);
            dataJSON.AddField("preloadAudioData", true);

            AssetImporter importer      = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(audioClip.GetInstanceID()));
            AudioImporter audioImporter = importer as AudioImporter;
            int           loadType;

            LoadTypeMap.TryGetValue(audioImporter.defaultSampleSettings.loadType, out loadType);
            audioClipJSON.AddField("loadType", loadType);

            /*
             * AssetImporter importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(audioClip.GetInstanceID()));
             * AudioImporter audioImporter = importer as AudioImporter;
             * PropertyInfo inspectorModeInfo = typeof(UnityEditor.SerializedObject).GetProperty ("inspectorMode", BindingFlags.NonPublic | BindingFlags.Instance);
             * UnityEditor.SerializedObject serializedObject = new UnityEditor.SerializedObject (audioImporter);
             * inspectorModeInfo.SetValue(serializedObject, UnityEditor.InspectorMode.Debug, null);
             * UnityEditor.SerializedProperty normalize = serializedObject.FindProperty ("m_Normalize");
             * audioClipJSON.AddField("normalize", normalize.boolValue);
             * audioClipJSON.AddField("ambisonic", audioImporter.ambisonic);
             * audioClipJSON.AddField("conversionMode", audioImporter.defaultSampleSettings.conversionMode);
             * audioClipJSON.AddField("quality", audioImporter.defaultSampleSettings.quality);
             * audioClipJSON.AddField("sampleRateOverride", audioImporter.defaultSampleSettings.sampleRateOverride);
             *
             * int compressionFormat;
             * CompressionFormatMap.TryGetValue(audioImporter.defaultSampleSettings.compressionFormat, out compressionFormat);
             * audioClipJSON.AddField("compressionFormat", compressionFormat);
             *
             * int sampleRateSetting;
             * SampleRateSettingMap.TryGetValue(audioImporter.defaultSampleSettings.sampleRateSetting, out sampleRateSetting);
             * audioClipJSON.AddField("sampleRateSetting", sampleRateSetting);
             *
             * int loadType;
             * LoadTypeMap.TryGetValue(audioImporter.defaultSampleSettings.loadType, out loadType);
             * audioClipJSON.AddField("loadType", loadType);
             *
             * audioClipJSON.AddField("forceToMono", audioImporter.forceToMono);
             * audioClipJSON.AddField("loadInBackground", audioImporter.loadInBackground);
             * audioClipJSON.AddField("preloadAudioData", audioImporter.preloadAudioData);
             * audioClipJSON.AddField("threeD", audioImporter.threeD);
             */
            return(audioClipJSON);
        }
Exemple #25
0
 public WXAudioClip(AudioClip _audioClip, GameObject _gameObject) : base(AssetDatabase.GetAssetPath(_audioClip.GetInstanceID()))
 {
     audioClip  = _audioClip;
     gameObject = _gameObject;
     if (unityAssetPath == null || unityAssetPath == "")
     {
         ErrorUtil.ExportErrorReporter.create()
         .setResource(this)
         .setGameObject(_gameObject)
         .error(ErrorUtil.ErrorCode.AudioClip_PathError, "audioClip文件的unity路径为空");
     }
 }
Exemple #26
0
    void Update()
    {
        if (source == null)
        {
            return;
        }

        if (!source.isPlaying)
        {
            _lastCalculatedAverage = 0f;
            if (thresholdEvents != null)
            {
                for (int e = 0; e < thresholdEvents.Length; ++e)
                {
                    thresholdEvents[e].Reset();
                }
            }
            return;
        }
        else
        {
            AudioClip newClip = source.clip;
            if (newClip != clip)
            {
                clip = newClip;

                int clipId = clip.GetInstanceID();
                if (!_cachedSamples.ContainsKey(clipId))
                {
                    //if there is a mask referenced by this sampler which corresponds to the sound, use those samples instead
                    float[] newSamples = null;
                    if (sampleMasks != null)
                    {
                        for (int m = 0; m < sampleMasks.Count; ++m)
                        {
                            if (sampleMasks[m].clip == clip)
                            {
                                newSamples = sampleMasks[m].values;
                            }
                        }
                    }
                    if (newSamples == null)
                    {
                        UnityEngine.Debug.Log("Could not find mask for " + clip.name + ", " + gameObject.name);
                        newSamples = LoadSamples(clip, stepSize, stepBuffer);
                    }

                    _cachedSamples[clipId] = newSamples;

                    //------------------------------------------------------------------
                    //If we're in editor, generate animationCurves containing the samples for debugging
                      #if UNITY_EDITOR
                    #region DEBUG_ANIMATION_CURVES
                    AnimationCurve curve = new AnimationCurve();
                    Keyframe[]     keys;
                    if (newSamples.Length < MAX_DEBUG_CURVE_KEYS)
                    {
                        keys = new Keyframe[newSamples.Length];
                        float keyLength = 1f / (float)keys.Length * clip.length;
                        for (int k = 0; k < keys.Length; ++k)
                        {
                            keys[k] = new Keyframe((float)k * keyLength, newSamples[k]);
                        }
                    }
                    else
                    {
                        keys = new Keyframe[MAX_DEBUG_CURVE_KEYS];
                        float keyLength  = 1f / (float)keys.Length * clip.length;
                        float clipLength = clip.length;
                        for (int k = 0; k < keys.Length; ++k)
                        {
                            keys[k] = new Keyframe((float)k * keyLength, _Read((float)k * keyLength, clipLength, newSamples));
                        }
                    }
                    curve.keys = keys;
                    _debugCurves.Add(curve);
                    #endregion DEBUG_ANIMATION_CURVES
                      #endif
                }

                samples = _cachedSamples[clipId];
            }

            //set the last-calculated-average
            _lastCalculatedAverage = _Read(source.time + fixedTimeOffset);


            //update all threshold events
            if (thresholdEvents != null)
            {
                //the maximum number of
                int readsPerFrame = 1;
                for (int t = 0; t < thresholdEvents.Length; ++t)
                {
                    if (thresholdEvents[t].readsPerFrame > readsPerFrame)
                    {
                        readsPerFrame = thresholdEvents[t].readsPerFrame;
                    }
                }

                if (eventsNextFramesBuffer == null || eventsNextFramesBuffer.Length != readsPerFrame)
                {
                    eventsNextFramesBuffer = new float[readsPerFrame];
                }
                for (int i = 0; i < eventsNextFramesBuffer.Length; ++i)
                {
                    eventsNextFramesBuffer[i] = _Read(source.time + fixedTimeOffset + (Time.deltaTime * (float)(i + 1)));
                }

                for (int t = 0; t < thresholdEvents.Length; ++t)
                {
                    if (thresholdEvents[t] != null)
                    {
                        thresholdEvents[t].Update(_lastCalculatedAverage, eventsNextFramesBuffer);
                    }
                }
            }
        }
    }