Advertisement
SharpShark

SpectrToJson

Jun 1st, 2025
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 4.46 KB | Gaming | 0 0
  1. // При запуске указываем закидываем папку со всеми аудиоклипами
  2. // Снимается спектрограмма и сохраняется в JSON
  3.  
  4. using UnityEngine;
  5. using UnityEditor;
  6. using System.IO;
  7. using System.Collections.Generic;
  8.  
  9. public class AudioSpectrumExporter : EditorWindow
  10. {
  11.     private DefaultAsset folder;
  12.     private int fftSize = 512;
  13.     private int stepMilliseconds = 50;
  14.     private FFTWindow fftWindow = FFTWindow.Blackman;
  15.  
  16.     [MenuItem("Tools/Batch Audio Spectrum Exporter")]
  17.     public static void ShowWindow()
  18.     {
  19.         GetWindow<AudioSpectrumExporter>("Batch Spectrum Exporter");
  20.     }
  21.  
  22.     private void OnGUI()
  23.     {
  24.         folder = (DefaultAsset)EditorGUILayout.ObjectField("Audio Folder", folder, typeof(DefaultAsset), false);
  25.         fftSize = EditorGUILayout.IntField("FFT Size", fftSize);
  26.         stepMilliseconds = EditorGUILayout.IntField("Step (ms)", stepMilliseconds);
  27.         fftWindow = (FFTWindow)EditorGUILayout.EnumPopup("FFT Window", fftWindow);
  28.  
  29.         if (GUILayout.Button("Export All Spectra"))
  30.         {
  31.             if (folder == null)
  32.             {
  33.                 Debug.LogError("Please assign a folder with AudioClips.");
  34.                 return;
  35.             }
  36.  
  37.             string folderPath = AssetDatabase.GetAssetPath(folder);
  38.             ExportAllSpectra(folderPath);
  39.         }
  40.     }
  41.  
  42.     private void ExportAllSpectra(string folderPath)
  43.     {
  44.         string[] audioGuids = AssetDatabase.FindAssets("t:AudioClip", new[] { folderPath });
  45.  
  46.         string exportFolder = EditorUtility.OpenFolderPanel("Select Folder to Save JSON", "", "");
  47.         if (string.IsNullOrEmpty(exportFolder)) return;
  48.  
  49.         foreach (string guid in audioGuids)
  50.         {
  51.             string path = AssetDatabase.GUIDToAssetPath(guid);
  52.             AudioClip clip = AssetDatabase.LoadAssetAtPath<AudioClip>(path);
  53.             if (clip == null)
  54.             {
  55.                 Debug.LogWarning($"Skipped invalid AudioClip at {path}");
  56.                 continue;
  57.             }
  58.  
  59.             Debug.Log($"Processing: {clip.name}");
  60.             ExportSpectrum(clip, exportFolder);
  61.         }
  62.  
  63.         Debug.Log("Spectrum export complete.");
  64.     }
  65.  
  66.     private void ExportSpectrum(AudioClip clip, string exportFolder)
  67.     {
  68.         float[] samples = new float[clip.samples * clip.channels];
  69.         clip.GetData(samples, 0);
  70.  
  71.         int channels = clip.channels;
  72.         int totalSamples = samples.Length / channels;
  73.         int stepSamples = Mathf.CeilToInt((stepMilliseconds / 1000f) * clip.frequency);
  74.         int spectrumCount = totalSamples / stepSamples;
  75.  
  76.         List<float[]> spectrumOverTime = new List<float[]>();
  77.         float[] segment = new float[fftSize];
  78.  
  79.         for (int i = 0; i < spectrumCount; i++)
  80.         {
  81.             int start = i * stepSamples;
  82.             if (start + fftSize >= totalSamples) break;
  83.  
  84.             for (int j = 0; j < fftSize; j++)
  85.             {
  86.                 segment[j] = samples[(start + j) * channels];
  87.             }
  88.  
  89.             AudioClip tempClip = AudioClip.Create("temp", fftSize, 1, clip.frequency, false);
  90.             tempClip.SetData(segment, 0);
  91.  
  92.             float[] spectrum = new float[fftSize];
  93.             AudioUtility.GetSpectrum(tempClip, spectrum, fftWindow);
  94.  
  95.             spectrumOverTime.Add(spectrum);
  96.             Object.DestroyImmediate(tempClip);
  97.         }
  98.  
  99.         string json = JsonHelper.ToJson(spectrumOverTime.ToArray(), true);
  100.         string savePath = Path.Combine(exportFolder, clip.name + "_spectrum.json");
  101.         File.WriteAllText(savePath, json);
  102.     }
  103.  
  104.     static class AudioUtility
  105.     {
  106.         public static void GetSpectrum(AudioClip clip, float[] spectrum, FFTWindow window)
  107.         {
  108.             var go = new GameObject("TempAudioSource");
  109.             var audioSource = go.AddComponent<AudioSource>();
  110.             audioSource.clip = clip;
  111.             audioSource.Play();
  112.  
  113.             for (int i = 0; i < 3; i++) audioSource.GetSpectrumData(spectrum, 0, window);
  114.             Object.DestroyImmediate(go);
  115.         }
  116.     }
  117.  
  118.     public static class JsonHelper
  119.     {
  120.         public static string ToJson<T>(T[] array, bool prettyPrint)
  121.         {
  122.             Wrapper<T> wrapper = new Wrapper<T> { Items = array };
  123.             return JsonUtility.ToJson(wrapper, prettyPrint);
  124.         }
  125.  
  126.         [System.Serializable]
  127.         private class Wrapper<T> { public T[] Items; }
  128.     }
  129. }
  130.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement