hello my script is having issues when I turn up the audio length to 70, it's causing it to save slower yet this dosn't happen in my other script, compare the two and fix my main script and return it fixed based off what you learn from my other script thanks.
'Main Script'
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
public class ACEStepRuntimeInference : MonoBehaviour
{
[Header("Server Settings")]
[Tooltip("Base URL of the inference server (no trailing slash)")]
public string serverBaseUrl = "http://localhost:8000";
code
Assistant
User
provide full script of my main script fixed ty
Assistant
User
I've accidently lost my "My Other Script' can you please return it in full for me?
Assistant
User
Assistant
Certainly! Here's a polished product description based on the README you provided:
AceStep - Unity Bridge: AI-Powered Music Generation Inside Unity
AceStep - Unity Bridge is a powerful Unity Editor integration that brings AI-driven music generation directly into your game development workflow. Seamlessly connect your Unity projects with the advanced AceStep AI music generator to create unique, dynamic soundtracks on the fly—no musical expertise required.
User
make it formatted for a text file and keep it short and sweet
Assistant
Sure! Here’s a concise, nicely formatted product description for a text file:
code
===============================================================================
AceStep - Unity Bridge
===============================================================================
Bring AI-powered music generation directly into your Unity Editor!
AceStep - Unity Bridge connects Unity with the advanced AceStep AI music generator,
allowing you to create unique, dynamic soundtracks in real-time — no musical skills needed.
Key Features:
- Generate songs from genres, moods, or lyrics inside Unity
- Instantly preview generated audio within the Editor
- Easy setup with included server script and intuitive interface
- Perfect for dynamic game soundtracks, rapid prototyping, and creative exploration
Requirements:
- A working AceStep installation with the 'infer-api-unity.py' server running
Start composing smarter and faster with AceStep - Unity Bridge!
===============================================================================
Made with 💙 for game developers and creative makers
===============================================================================
[Header("Input Parameters")]
public string checkpoint_path = "";
public bool bf16 = true;
public bool torch_compile = false;
public int device_id = 0;
[Tooltip("Ignored by server")]
public string output_path = ""; // Kept for completeness
public float audio_duration = 10f;
[TextArea(2, 5)]
public string prompt = "";
[TextArea(2, 5)]
public string lyrics = "";
public int infer_step = 50;
public float guidance_scale = 7.5f;
public string scheduler_type = "euler";
public string cfg_type = "apg";
public float omega_scale = 1.0f;
[Tooltip("Seeds for random generator")]
public List<int> actual_seeds = new List<int> { };
public float guidance_interval = 1.0f;
public float guidance_interval_decay = 0.0f;
public float min_guidance_scale = 0.0f;
public bool use_erg_tag = false;
public bool use_erg_lyric = false;
public bool use_erg_diffusion = false;
[Tooltip("OSS steps")]
public List<int> oss_steps = new List<int> { };
public float guidance_scale_text = 0.0f;
public float guidance_scale_lyric = 0.0f;
[Header("Output")]
[Tooltip("Local folder to save downloaded audio")]
public string localSaveFolder;
[Header("Generation Result")]
[Tooltip("AudioClip loaded from the generated audio file")]
public AudioClip GenerationResult;
[Header("Generation State")]
[Tooltip("True when generation is in progress")]
public bool IsGenerating = false;
private ACEStepClient client;
void Awake()
{
if (string.IsNullOrEmpty(localSaveFolder))
{
localSaveFolder = Path.Combine(Application.persistentDataPath, "GeneratedAudio");
}
if (!Directory.Exists(localSaveFolder))
{
Directory.CreateDirectory(localSaveFolder);
}
client = GetComponent<ACEStepClient>();
if (client == null)
{
client = gameObject.AddComponent<ACEStepClient>();
}
client.serverBaseUrl = serverBaseUrl;
}
[ContextMenu("Start Generate Audio")]
public void StartGenerate()
{
if (IsGenerating)
{
Debug.LogWarning("Generation is already in progress.");
return;
}
// Reset generation result & output path before starting new generation
GenerationResult = null;
output_path = "";
Debug.Log($"Starting generation with prompt: \"{prompt}\" and lyrics: \"{lyrics}\"");
IsGenerating = true;
var input = BuildACEStepInput();
// Add debug - to confirm input values
Debug.Log($"ACEStepInput built: checkpoint_path={input.checkpoint_path}, prompt=\"{input.prompt}\", lyrics=\"{input.lyrics}\", seeds count={input.actual_seeds.Count}");
client.GenerateAudio(input, OnGenerateSuccess, OnGenerateError);
}
private ACEStepInput BuildACEStepInput()
{
return new ACEStepInput()
{
checkpoint_path = checkpoint_path,
bf16 = bf16,
torch_compile = torch_compile,
device_id = device_id,
output_path = output_path,
audio_duration = audio_duration,
prompt = prompt,
lyrics = lyrics,
infer_step = infer_step,
guidance_scale = guidance_scale,
scheduler_type = scheduler_type,
cfg_type = cfg_type,
omega_scale = omega_scale,
actual_seeds = new List<int>(actual_seeds),
guidance_interval = guidance_interval,
guidance_interval_decay = guidance_interval_decay,
min_guidance_scale = min_guidance_scale,
use_erg_tag = use_erg_tag,
use_erg_lyric = use_erg_lyric,
use_erg_diffusion = use_erg_diffusion,
oss_steps = new List<int>(oss_steps),
guidance_scale_text = guidance_scale_text,
guidance_scale_lyric = guidance_scale_lyric,
};
}
private void OnGenerateSuccess(ACEStepOutput output)
{
Debug.Log("Generation success! Server returned output path: " + output.output_path);
if (string.IsNullOrEmpty(output.output_path))
{
Debug.LogWarning("Output path from server is empty");
SetFilePathText("No output file returned from server");
IsGenerating = false;
return;
}
// Assign output path immediately to track correctly
output_path = output.output_path;
// Start download coroutine with the filename returned by the server
StartCoroutine(DownloadAndSaveAudio(output.output_path));
}
private void OnGenerateError(string error)
{
Debug.LogError("Generation failed: " + error);
SetFilePathText("Generation failed: " + error);
IsGenerating = false;
}
private IEnumerator DownloadAndSaveAudio(string filename)
{
if (string.IsNullOrEmpty(filename))
{
Debug.LogError("No filename received from server to download.");
IsGenerating = false;
yield break;
}
string downloadUrl = $"{serverBaseUrl.TrimEnd('/')}/files/{filename}";
using (UnityWebRequest www = UnityWebRequest.Get(downloadUrl))
{
yield return www.SendWebRequest();
private AudioType GetAudioTypeFromFileExtension(string filePath)
{
string ext = Path.GetExtension(filePath).ToLowerInvariant();
switch (ext)
{
case ".wav": return AudioType.WAV;
case ".mp3": return AudioType.MPEG;
case ".ogg": return AudioType.OGGVORBIS;
case ".aiff": return AudioType.AIFF;
case ".mod": return AudioType.MOD;
case ".xm": return AudioType.XM;
case ".it": return AudioType.IT;
case ".s3m": return AudioType.S3M;
default:
Debug.LogWarning($"Unknown audio extension '{ext}', defaulting to WAV");
return AudioType.WAV;
}
}
}
'My Other Script'
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine.Networking;
using Unity.EditorCoroutines.Editor;
public class AceStepEditorWindow : EditorWindow
{
private Texture2D logoTexture;
if (error)
{
generateStatus = $"Failed to download generated audio: {www.error}";
isGenerating = false;
Repaint();
yield break;
}
byte[] audioBytes = www.downloadHandler.data;
string localFolder = input.output_path;
if (string.IsNullOrEmpty(localFolder) || !Directory.Exists(localFolder))
{
generateStatus = $"Invalid output folder selected: {localFolder}";
isGenerating = false;
Repaint();
yield break;
}
string localPath = Path.Combine(localFolder, filename);
try
{
File.WriteAllBytes(localPath, audioBytes);
AssetDatabase.Refresh();
generatedAudioPath = localPath;
generateStatus = $"Saved audio to: {localPath}";
// Defer loading the clip to allow Unity to import the file
EditorApplication.delayCall += () =>
{
LoadAudioClipFromPath(localPath);
SelectGeneratedAudioAsset();
Repaint();
};
}
catch (Exception e)
{
generateStatus = $"Error saving file: {e.Message}";
}
finally
{
isGenerating = false;
Repaint();
}
}
private void LoadAudioClipFromPath(string fullPath)
{
Debug.Log($"Attempting to load audio clip from path: {fullPath}");
if (!fullPath.StartsWith(Application.dataPath))
{
Debug.LogWarning("Generated audio file is outside the Assets folder and cannot be loaded.");
generatedClip = null;
return;
}
string relativePath = "Assets" + fullPath.Substring(Application.dataPath.Length);
generatedAudioPath = relativePath;
Debug.Log("Loading audio clip at relative path: " + relativePath);
generatedClip = AssetDatabase.LoadAssetAtPath<AudioClip>(relativePath);
if (generatedClip == null)
generateStatus = "Failed to load audio clip from saved file.";
else
{
generateStatus = "Audio clip loaded. You can now play it.";
isPlaying = false;
playPosition = 0f;
}
}
private void SelectGeneratedAudioAsset()
{
if (string.IsNullOrEmpty(generatedAudioPath))
return;
UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(generatedAudioPath);
if (obj != null)
{
Selection.activeObject = obj;
EditorGUIUtility.PingObject(obj);
}
}
private void OnGenerationError(string errorMsg)
{
generateStatus = "Generation failed: " + errorMsg;
isGenerating = false;
Repaint();
}
private static class AudioUtil
{
private static readonly Type audioUtilType;
private static readonly System.Reflection.MethodInfo playClipMethod;
private static readonly System.Reflection.MethodInfo stopClipMethod;
private static readonly System.Reflection.MethodInfo setClipSamplePositionMethod;
static AudioUtil()
{
audioUtilType = typeof(AudioImporter).Assembly.GetType("UnityEditor.AudioUtil");
setClipSamplePositionMethod = audioUtilType.GetMethod("SetClipSamplePosition", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic, null, new Type[] { typeof(AudioClip), typeof(int) }, null);
}
public static void PlayClip(AudioClip clip)
{
playClipMethod?.Invoke(null, new object[] { clip });
}
public static void StopClip(AudioClip clip)
{
stopClipMethod?.Invoke(null, new object[] { clip });
}
public static void SetClipSamplePosition(AudioClip clip, int positionSamples)
{
setClipSamplePositionMethod?.Invoke(null, new object[] { clip, positionSamples });
}
}
private void PlayClipAtPosition(AudioClip clip, float timePosition)
{
if (clip == null) return;
int samplePos = Mathf.Clamp((int)(timePosition * clip.frequency), 0, clip.samples - 1);
AudioUtil.SetClipSamplePosition(clip, samplePos);
}
class ACEStepClientGenerationRunner : MonoBehaviour
{
private static ACEStepClientGenerationRunner _instance;
private ACEStepClient client;
public ACEStepClientGenerationRunner(AceStepEditorWindow window)
{
if (_instance == null)
{
GameObject go = new GameObject("ACEStepClientGenerationRunner");
go.hideFlags = HideFlags.HideAndDontSave;
_instance = go.AddComponent<ACEStepClientGenerationRunner>();
}
client = _instance.gameObject.GetComponent<ACEStepClient>();
if (client == null)
client = _instance.gameObject.AddComponent<ACEStepClient>();
}
public void GenerateAudio(ACEStepInput input, Action<ACEStepOutput> onSuccess, Action<string> onError)
{
_instance.StartCoroutine(client.GenerateAudioRoutine(input, onSuccess, onError));
}
}
}
The issue where increasing audio_duration to 70 causes slower saving in your Main Script, but not in your other Editor script, is likely related to how the output folder and file saving/loading is handled differently between them.
Key Differences Related to Saving/Loading:
Aspect
Main Script (Runtime)
Other Script (Editor)
Output Folder Usage
Uses localSaveFolder in Application.persistentDataPath (separate location from Unity Assets folder)
Uses user drag-dropped folder in the Unity project (under Assets)
Saving File Path
Saves with filename directly under localSaveFolder in persistent data path
Saves the file in explicitly set input.output_path (which is a folder in Unity Assets folder)
Loading AudioClip
Loads via UnityWebRequestMultimedia.GetAudioClip from file:// URI asynchronously
Loads via AssetDatabase.LoadAssetAtPath<AudioClip>() synchronously after an AssetDatabase.Refresh()
Unity Import Step
None explicitly (just loading raw file via WWW)
Explicit AssetDatabase.Refresh() to trigger Unity import pipeline
AudioClip Availability & Importing
May take longer or fail to load larger files because they're outside Unity's asset database and importing is bypassed
Files saved inside Unity Assets folder are imported incrementally, so play/preview is quick and smooth
Why does this matter?
Your Runtime Main Script downloads and saves the audio to a folder outside Unity's Assets folder (Application.persistentDataPath).
It then tries to load an AudioClip from disk using UnityWebRequestMultimedia.GetAudioClip(file://...).
For long audio clips (like 70s), this approach can be slow because it loads/decodes the audio completely at runtime and depends on file I/O speed and memory.
Your Editor script, on the other hand:
Saves directly into a Unity project folder.
Calls AssetDatabase.Refresh() immediately after saving, so Unity re-imports the audio file and makes a cached version accessible.
Loads audio using AssetDatabase.LoadAssetAtPath<AudioClip>(), which accesses the Unity-imported asset directly and is much faster.
This import/asset management pipeline is optimized internally by Unity, making large audio files ready for playback much faster.
Fix for your Main Script based on this analysis
You want to replicate the Editor approach to the extent possible during runtime.
Options:
Save inside Unity Asset folder (if possible) and trigger asset import from script (only works in Editor, not in builds).
This is only viable for Editor or Editor-only scripts.
Use UnityWebRequestMultimedia.GetAudioClip in streaming mode with careful memory management.
Avoid loading very long audio clips fully into memory at once.
Instead of relying on immediate load via WWW, wait until after the file is fully written and then create the AudioClip using UnityEngine.Audio.AudioClip.Create and streaming if needed.
Optimize your coroutine to handle large files efficiently.
Immediate improvements you can make in your Main Script:
After saving the file, release the www resources immediately and delay the audio load slightly, to avoid busy I/O.
Use asynchronous chunked downloading if the server supports it.
You can also add logs that time download and load separately to identify which part slows down.
Code changes to fix and improve your Main Script's DownloadAndSaveAudio and loading routine:
1. Add a tiny wait or delayed loading after save, to give the system time to flush disk operations:
csharp
// After writing the file bytes successfully:
try
{
File.WriteAllBytes(localPath, audioBytes);
Debug.Log($"Saved audio file locally at: {localPath}");
}
catch (Exception e)
{
Debug.LogError($"Error saving audio file: {e.Message}");
SetFilePathText("Error saving audio file: " + e.Message);
IsGenerating = false;
yield break;
}
// Add tiny delay to allow file system to complete flush and reduce read contention.
yield return new WaitForSeconds(0.1f);
SetFilePathText(localPath);
IsGenerating = false;
2. Modify LoadAudioClipFromFile to use streaming AudioClip mode for large audio:
Unitys UnityWebRequestMultimedia.GetAudioClip()supports streaming if you useaudioClip.loadType = AudioClipLoadType.Streaming`.
Since you use the default method, it might be loading full audio into memory causing slowdown.
Modify the loading part:
csharp
private IEnumerator LoadAudioClipFromFile(string filePath)
{
if (!File.Exists(filePath))
{
Debug.LogError($"Audio file not found on disk: {filePath}");
GenerationResult = null;
yield break;
}
string uri = "file://" + filePath;
AudioType audioType = GetAudioTypeFromFileExtension(filePath);
using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(uri, audioType))
{
var audioDownloadHandler = (DownloadHandlerAudioClip)www.downloadHandler;
// Enable streaming for large audio files (e.g., 70 seconds)
audioDownloadHandler.streamAudio = true;
yield return www.SendWebRequest();
#if UNITY_2020_1_OR_NEWER
bool isError = www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError;
#else
bool isError = www.isNetworkError || www.isHttpError;
#endif
if (isError)
{
Debug.LogError($"Failed to load audio clip from file: {www.error}");
GenerationResult = null;
}
else
{
var clip = DownloadHandlerAudioClip.GetContent(www);
if (clip == null)
{
Debug.LogError("Loaded AudioClip is null");
GenerationResult = null;
}
else
{
Debug.Log($"AudioClip loaded successfully from {filePath}");
GenerationResult = clip;
output_path = filePath;
}
}
}
}
3. Alternatively, consider streaming from your HTTP server without download + write file step (if latency/bandwidth is acceptable).
Summary of Fixes
Use audioDownloadHandler.streamAudio = true; when calling UnityWebRequestMultimedia.GetAudioClip() to avoid loading the entire file into memory at once.
Add a small delay (yield return new WaitForSeconds(0.1f);) after the file write to allow disk flush.
Keep your file save structure but consider saving files inside the Unity project folder (Editor-only) if you want to leverage AssetDatabase importing for faster load.
For runtime builds, streaming mode is the most practical fix to performance issues with large audio clips.
Why didn't this happen in your Editor script?
Editor script saves inside Unity Assets: automatic import optimizes the audio asset for fast loading.
Editor script loads the asset with AssetDatabase.LoadAssetAtPath instead of loading raw bytes + decoding.
Runtime script loads raw file from disk and fully decodes, which is expensive and slower for long clips, especially at 70s.
If you want, I can also help you refactor your Main Script to optionally save into Unity Assets folder if running inside Editor to directly benefit from the Editor loading approach.
Let me know!
Certainly! Below is your Main Script fixed with streaming audio loading and a slight delay after file save to improve performance for long audio (like 70s). The main changes are in DownloadAndSaveAudio and LoadAudioClipFromFile as explained.
csharp
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
public class ACEStepRuntimeInference : MonoBehaviour
{
[Header("Server Settings")]
[Tooltip("Base URL of the inference server (no trailing slash)")]
public string serverBaseUrl = "http://localhost:8000";
[Header("Input Parameters")]
public string checkpoint_path = "";
public bool bf16 = true;
public bool torch_compile = false;
public int device_id = 0;
[Tooltip("Ignored by server")]
public string output_path = ""; // Kept for completeness
public float audio_duration = 10f;
[TextArea(2, 5)]
public string prompt = "";
[TextArea(2, 5)]
public string lyrics = "";
public int infer_step = 50;
public float guidance_scale = 7.5f;
public string scheduler_type = "euler";
public string cfg_type = "apg";
public float omega_scale = 1.0f;
[Tooltip("Seeds for random generator")]
public List<int> actual_seeds = new List<int> { };
public float guidance_interval = 1.0f;
public float guidance_interval_decay = 0.0f;
public float min_guidance_scale = 0.0f;
public bool use_erg_tag = false;
public bool use_erg_lyric = false;
public bool use_erg_diffusion = false;
[Tooltip("OSS steps")]
public List<int> oss_steps = new List<int> { };
public float guidance_scale_text = 0.0f;
public float guidance_scale_lyric = 0.0f;
[Header("Output")]
[Tooltip("Local folder to save downloaded audio")]
public string localSaveFolder;
[Header("Generation Result")]
[Tooltip("AudioClip loaded from the generated audio file")]
public AudioClip GenerationResult;
[Header("Generation State")]
[Tooltip("True when generation is in progress")]
public bool IsGenerating = false;
private ACEStepClient client;
void Awake()
{
if (string.IsNullOrEmpty(localSaveFolder))
{
localSaveFolder = Path.Combine(Application.persistentDataPath, "GeneratedAudio");
}
if (!Directory.Exists(localSaveFolder))
{
Directory.CreateDirectory(localSaveFolder);
}
client = GetComponent<ACEStepClient>();
if (client == null)
{
client = gameObject.AddComponent<ACEStepClient>();
}
client.serverBaseUrl = serverBaseUrl;
}
[ContextMenu("Start Generate Audio")]
public void StartGenerate()
{
if (IsGenerating)
{
Debug.LogWarning("Generation is already in progress.");
return;
}
// Reset generation result & output path before starting new generation
GenerationResult = null;
output_path = "";
Debug.Log($"Starting generation with prompt: \"{prompt}\" and lyrics: \"{lyrics}\"");
IsGenerating = true;
var input = BuildACEStepInput();
// Add debug - to confirm input values
Debug.Log($"ACEStepInput built: checkpoint_path={input.checkpoint_path}, prompt=\"{input.prompt}\", lyrics=\"{input.lyrics}\", seeds count={input.actual_seeds.Count}");
client.GenerateAudio(input, OnGenerateSuccess, OnGenerateError);
}
private ACEStepInput BuildACEStepInput()
{
return new ACEStepInput()
{
checkpoint_path = checkpoint_path,
bf16 = bf16,
torch_compile = torch_compile,
device_id = device_id,
output_path = output_path,
audio_duration = audio_duration,
prompt = prompt,
lyrics = lyrics,
infer_step = infer_step,
guidance_scale = guidance_scale,
scheduler_type = scheduler_type,
cfg_type = cfg_type,
omega_scale = omega_scale,
actual_seeds = new List<int>(actual_seeds),
guidance_interval = guidance_interval,
guidance_interval_decay = guidance_interval_decay,
min_guidance_scale = min_guidance_scale,
use_erg_tag = use_erg_tag,
use_erg_lyric = use_erg_lyric,
use_erg_diffusion = use_erg_diffusion,
oss_steps = new List<int>(oss_steps),
guidance_scale_text = guidance_scale_text,
guidance_scale_lyric = guidance_scale_lyric,
};
}
private void OnGenerateSuccess(ACEStepOutput output)
{
Debug.Log("Generation success! Server returned output path: " + output.output_path);
if (string.IsNullOrEmpty(output.output_path))
{
Debug.LogWarning("Output path from server is empty");
SetFilePathText("No output file returned from server");
IsGenerating = false;
return;
}
// Assign output path immediately to track correctly
output_path = output.output_path;
// Start download coroutine with the filename returned by the server
StartCoroutine(DownloadAndSaveAudio(output.output_path));
}
private void OnGenerateError(string error)
{
Debug.LogError("Generation failed: " + error);
SetFilePathText("Generation failed: " + error);
IsGenerating = false;
}
private IEnumerator DownloadAndSaveAudio(string filename)
{
if (string.IsNullOrEmpty(filename))
{
Debug.LogError("No filename received from server to download.");
IsGenerating = false;
yield break;
}
string downloadUrl = $"{serverBaseUrl.TrimEnd('/')}/files/{filename}";
using (UnityWebRequest www = UnityWebRequest.Get(downloadUrl))
{
yield return www.SendWebRequest();
#if UNITY_2020_1_OR_NEWER
bool error = www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError;
#else
bool error = www.isNetworkError || www.isHttpError;
#endif
if (error)
{
Debug.LogError($"Failed to download generated audio: {www.error}");
SetFilePathText("Download failed: " + www.error);
IsGenerating = false;
yield break;
}
byte[] audioBytes = www.downloadHandler.data;
if (!Directory.Exists(localSaveFolder))
{
try
{
Directory.CreateDirectory(localSaveFolder);
}
catch (Exception e)
{
Debug.LogError($"Failed to create local save directory: {e.Message}");
SetFilePathText("Failed to create save folder: " + e.Message);
IsGenerating = false;
yield break;
}
}
string localPath = Path.Combine(localSaveFolder, filename);
try
{
File.WriteAllBytes(localPath, audioBytes);
Debug.Log($"Saved audio file locally at: {localPath}");
}
catch (Exception e)
{
Debug.LogError($"Error saving audio file: {e.Message}");
SetFilePathText("Error saving audio file: " + e.Message);
IsGenerating = false;
yield break;
}
// Allow a small delay to avoid disk I/O contention on large files
yield return new WaitForSeconds(0.1f);
SetFilePathText(localPath);
IsGenerating = false;
}
}
private void SetFilePathText(string pathOrMessage)
{
// If pathOrMessage is a valid existing file path, try to load it as an AudioClip via file:// URI
if (!string.IsNullOrEmpty(pathOrMessage) && File.Exists(pathOrMessage))
{
StartCoroutine(LoadAudioClipFromFile(pathOrMessage));
}
else
{
// It's probably an error message or invalid path. Clear clip and log message.
Debug.LogWarning(pathOrMessage);
GenerationResult = null;
}
}
private IEnumerator LoadAudioClipFromFile(string filePath)
{
if (!File.Exists(filePath))
{
Debug.LogError($"Audio file not found on disk: {filePath}");
GenerationResult = null;
yield break;
}
string uri = "file://" + filePath;
AudioType audioType = GetAudioTypeFromFileExtension(filePath);
using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(uri, audioType))
{
// Enable streaming for improving performance on large files
var audioDownloadHandler = (DownloadHandlerAudioClip)www.downloadHandler;
audioDownloadHandler.streamAudio = true;
yield return www.SendWebRequest();
#if UNITY_2020_1_OR_NEWER
bool isError = www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError;
#else
bool isError = www.isNetworkError || www.isHttpError;
#endif
if (isError)
{
Debug.LogError($"Failed to load audio clip from file: {www.error}");
GenerationResult = null;
}
else
{
var clip = DownloadHandlerAudioClip.GetContent(www);
if (clip == null)
{
Debug.LogError("Loaded AudioClip is null");
GenerationResult = null;
}
else
{
Debug.Log($"AudioClip loaded successfully from {filePath}");
GenerationResult = clip;
output_path = filePath;
}
}
}
}
private AudioType GetAudioTypeFromFileExtension(string filePath)
{
string ext = Path.GetExtension(filePath).ToLowerInvariant();
switch (ext)
{
case ".wav": return AudioType.WAV;
case ".mp3": return AudioType.MPEG;
case ".ogg": return AudioType.OGGVORBIS;
case ".aiff": return AudioType.AIFF;
case ".mod": return AudioType.MOD;
case ".xm": return AudioType.XM;
case ".it": return AudioType.IT;
case ".s3m": return AudioType.S3M;
default:
Debug.LogWarning($"Unknown audio extension '{ext}', defaulting to WAV");
return AudioType.WAV;
}
}
}
Explanation of fixes:
Streaming audio load enabled:audioDownloadHandler.streamAudio = true; during UnityWebRequestMultimedia.GetAudioClip(). This will reduce memory pressure and loading time for large audio files.
Small delay after file write:yield return new WaitForSeconds(0.1f); allows disk system to finish flush operations before attempting to load.
Otherwise code is unchanged to keep logic consistent.
This should help your runtime script handle longer audio durations (70s) without large slowdowns when saving or loading audio clips.
If you want further improvements (e.g., caching, asynchronous processing, etc.), feel free to ask!
Certainly! Here is your full "My Other Script" as you originally provided it:
csharp
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine.Networking;
using Unity.EditorCoroutines.Editor;
public class AceStepEditorWindow : EditorWindow
{
private Texture2D logoTexture;
// The input object
private ACEStepInput input = new ACEStepInput()
{
checkpoint_path = "",
bf16 = true,
torch_compile = false,
device_id = 0,
output_path = "",
audio_duration = 10f,
prompt = "female singer, edm, drums, bass, synth",
lyrics = "[verse]\nThank you for buying my product,\nYou keep me alive,\nThank you for buying my product,\nYou're my favorite person alive.",
infer_step = 50,
guidance_scale = 7.5f,
scheduler_type = "euler",
cfg_type = "apg",
omega_scale = 0f,
actual_seeds = new List<int>() { },
guidance_interval = 1f,
guidance_interval_decay = 0f,
min_guidance_scale = 0f,
use_erg_tag = true,
use_erg_lyric = false,
use_erg_diffusion = true,
oss_steps = new List<int>() { },
guidance_scale_text = 0f,
guidance_scale_lyric = 0f,
};
// Server URL (base URL - no trailing slash)
private string server_url = "http://localhost:8000";
// Generated audio variables
private string generatedAudioPath = "";
private AudioClip generatedClip;
private bool isPlaying = false;
private float playPosition = 0f;
private Vector2 scrollPos;
private bool isGenerating = false;
private string generateStatus = "";
private ACEStepClientGenerationRunner clientRunner;
private Rect dragDropAreaRect;
[MenuItem("Tools/AceStep")]
public static void ShowWindow()
{
var window = GetWindow<AceStepEditorWindow>();
window.titleContent = new GUIContent("AceStep");
window.minSize = new Vector2(600, 700);
window.Show();
}
private void OnEnable()
{
logoTexture = Resources.Load<Texture2D>("AceStepLogo");
clientRunner = new ACEStepClientGenerationRunner(this);
}
private void OnDisable()
{
if (generatedClip != null)
DestroyImmediate(generatedClip, true);
}
void OnGUI()
{
DrawLogo();
scrollPos = EditorGUILayout.BeginScrollView(scrollPos);
GUILayout.Space(10);
DrawFolderDragDropArea();
GUILayout.Space(10);
EditorGUILayout.LabelField("Server URL (no trailing slash)", EditorStyles.boldLabel);
server_url = EditorGUILayout.TextField(server_url);
GUILayout.Space(10);
EditorGUILayout.LabelField("ACEStep Parameters", EditorStyles.boldLabel);
DrawInputFields();
GUILayout.Space(20);
EditorGUI.BeginDisabledGroup(isGenerating);
if (GUILayout.Button("GENERATE SONG", GUILayout.Height(40)))
{
if (string.IsNullOrEmpty(input.output_path))
{
EditorUtility.DisplayDialog("Error", "Please drag & drop an output folder before generating.", "OK");
}
else
{
generateStatus = "Starting generation...";
isGenerating = true;
generatedAudioPath = "";
if (generatedClip != null)
{
DestroyImmediate(generatedClip, true);
generatedClip = null;
}
isPlaying = false;
playPosition = 0f;
clientRunner.GenerateAudio(input, OnGenerationSuccess, OnGenerationError);
}
}
EditorGUI.EndDisabledGroup();
GUILayout.Space(10);
if (isGenerating)
{
EditorGUILayout.HelpBox(generateStatus, MessageType.Info);
}
else if (!string.IsNullOrEmpty(generatedAudioPath) && generatedClip != null)
{
}
else if (!string.IsNullOrEmpty(generateStatus))
{
EditorGUILayout.HelpBox(generateStatus, MessageType.Info);
}
EditorGUILayout.EndScrollView();
}
private void DrawLogo()
{
if (logoTexture != null)
{
float maxWidth = position.width * 0.8f;
float ratio = (float)logoTexture.height / logoTexture.width;
float width = Mathf.Min(maxWidth, logoTexture.width);
float height = width * ratio;
GUILayout.Space(10);
Rect rect = GUILayoutUtility.GetRect(width, height, GUILayout.ExpandWidth(false));
rect.x = (position.width - width) / 2;
EditorGUI.DrawPreviewTexture(rect, logoTexture, null, ScaleMode.ScaleToFit);
GUILayout.Space(10);
}
else
{
EditorGUILayout.HelpBox("Logo 'AceStepLogo.png' not found in Resources folder.", MessageType.Warning);
}
}
private void DrawFolderDragDropArea()
{
GUILayout.Label("Output Folder (drag & drop your Unity folder here)", EditorStyles.boldLabel);
dragDropAreaRect = GUILayoutUtility.GetRect(0, 50, GUILayout.ExpandWidth(true));
GUI.Box(dragDropAreaRect, string.IsNullOrEmpty(input.output_path) ?
"Drag & Drop Output Folder Here" : $"Output Folder:\n{input.output_path}", EditorStyles.helpBox);
Event evt = Event.current;
if ((evt.type == EventType.DragUpdated || evt.type == EventType.DragPerform) && dragDropAreaRect.Contains(evt.mousePosition))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
if (evt.type == EventType.DragPerform)
{
DragAndDrop.AcceptDrag();
foreach (var draggedObject in DragAndDrop.objectReferences)
{
string path = AssetDatabase.GetAssetPath(draggedObject);
if (!string.IsNullOrEmpty(path) && AssetDatabase.IsValidFolder(path))
{
input.output_path = path;
GUI.FocusControl(null);
break;
}
}
evt.Use();
}
}
}
private void DrawInputFields()
{
input.checkpoint_path = EditorGUILayout.TextField("Checkpoint Path", input.checkpoint_path);
input.bf16 = EditorGUILayout.Toggle("bf16", input.bf16);
input.torch_compile = EditorGUILayout.Toggle("torch_compile", input.torch_compile);
input.device_id = EditorGUILayout.IntField("device_id", input.device_id);
input.audio_duration = EditorGUILayout.FloatField("audio_duration", input.audio_duration);
EditorGUILayout.LabelField("Prompt");
input.prompt = EditorGUILayout.TextArea(input.prompt, GUILayout.Height(60));
EditorGUILayout.LabelField("Lyrics");
input.lyrics = EditorGUILayout.TextArea(input.lyrics, GUILayout.Height(60));
input.infer_step = EditorGUILayout.IntField("infer_step", input.infer_step);
input.guidance_scale = EditorGUILayout.FloatField("guidance_scale", input.guidance_scale);
string[] schedulerOptions = new string[] { "euler", "heun" };
int schedulerSelectedIndex = Array.IndexOf(schedulerOptions, input.scheduler_type);
if (schedulerSelectedIndex < 0) schedulerSelectedIndex = 0;
schedulerSelectedIndex = EditorGUILayout.Popup("scheduler_type", schedulerSelectedIndex, schedulerOptions);
input.scheduler_type = schedulerOptions[schedulerSelectedIndex];
string[] cfgOptions = new string[] { "cfg", "apg", "cfg_star" };
int cfgSelectedIndex = Array.IndexOf(cfgOptions, input.cfg_type);
if (cfgSelectedIndex < 0) cfgSelectedIndex = 1;
cfgSelectedIndex = EditorGUILayout.Popup("cfg_type", cfgSelectedIndex, cfgOptions);
input.cfg_type = cfgOptions[cfgSelectedIndex];
input.omega_scale = EditorGUILayout.FloatField("omega_scale", input.omega_scale);
DrawIntListField("actual_seeds", input.actual_seeds);
input.guidance_interval = EditorGUILayout.FloatField("guidance_interval", input.guidance_interval);
input.guidance_interval_decay = EditorGUILayout.FloatField("guidance_interval_decay", input.guidance_interval_decay);
input.min_guidance_scale = EditorGUILayout.FloatField("min_guidance_scale", input.min_guidance_scale);
input.use_erg_tag = EditorGUILayout.Toggle("use_erg_tag", input.use_erg_tag);
input.use_erg_lyric = EditorGUILayout.Toggle("use_erg_lyric", input.use_erg_lyric);
input.use_erg_diffusion = EditorGUILayout.Toggle("use_erg_diffusion", input.use_erg_diffusion);
DrawIntListField("oss_steps", input.oss_steps);
input.guidance_scale_text = EditorGUILayout.FloatField("guidance_scale_text", input.guidance_scale_text);
input.guidance_scale_lyric = EditorGUILayout.FloatField("guidance_scale_lyric", input.guidance_scale_lyric);
}
private void DrawIntListField(string label, List<int> list)
{
EditorGUILayout.LabelField(label);
if (list == null) list = new List<int>();
EditorGUI.indentLevel++;
int removeIndex = -1;
for (int i = 0; i < list.Count; i++)
{
EditorGUILayout.BeginHorizontal();
list[i] = EditorGUILayout.IntField(list[i]);
if (GUILayout.Button("-", GUILayout.Width(24)))
{
removeIndex = i;
}
EditorGUILayout.EndHorizontal();
}
if (removeIndex >= 0)
list.RemoveAt(removeIndex);
if (GUILayout.Button("+ Add " + label))
list.Add(0);
EditorGUI.indentLevel--;
}
private void OnGenerationSuccess(ACEStepOutput output)
{
generateStatus = "Generation succeeded! Downloading file...";
EditorCoroutineUtility.StartCoroutineOwnerless(DownloadAndSaveAudio(output.output_path));
}
private IEnumerator DownloadAndSaveAudio(string filename)
{
if (string.IsNullOrEmpty(filename))
{
generateStatus = "Error: No filename received from server.";
isGenerating = false;
Repaint();
yield break;
}
string downloadUrl = $"{server_url.TrimEnd('/')}/files/{filename}";
UnityWebRequest www = UnityWebRequest.Get(downloadUrl);
yield return www.SendWebRequest();
#if UNITY_2020_1_OR_NEWER
bool error = www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError;
#else
bool error = www.isNetworkError || www.isHttpError;
#endif
if (error)
{
generateStatus = $"Failed to download generated audio: {www.error}";
isGenerating = false;
Repaint();
yield break;
}
byte[] audioBytes = www.downloadHandler.data;
string localFolder = input.output_path;
if (string.IsNullOrEmpty(localFolder) || !Directory.Exists(localFolder))
{
generateStatus = $"Invalid output folder selected: {localFolder}";
isGenerating = false;
Repaint();
yield break;
}
string localPath = Path.Combine(localFolder, filename);
try
{
File.WriteAllBytes(localPath, audioBytes);
AssetDatabase.Refresh();
generatedAudioPath = localPath;
generateStatus = $"Saved audio to: {localPath}";
// Defer loading the clip to allow Unity to import the file
EditorApplication.delayCall += () =>
{
LoadAudioClipFromPath(localPath);
SelectGeneratedAudioAsset();
Repaint();
};
}
catch (Exception e)
{
generateStatus = $"Error saving file: {e.Message}";
}
finally
{
isGenerating = false;
Repaint();
}
}
private void LoadAudioClipFromPath(string fullPath)
{
Debug.Log($"Attempting to load audio clip from path: {fullPath}");
if (!fullPath.StartsWith(Application.dataPath))
{
Debug.LogWarning("Generated audio file is outside the Assets folder and cannot be loaded.");
generatedClip = null;
return;
}
string relativePath = "Assets" + fullPath.Substring(Application.dataPath.Length);
generatedAudioPath = relativePath;
Debug.Log("Loading audio clip at relative path: " + relativePath);
generatedClip = AssetDatabase.LoadAssetAtPath<AudioClip>(relativePath);
if (generatedClip == null)
generateStatus = "Failed to load audio clip from saved file.";
else
{
generateStatus = "Audio clip loaded. You can now play it.";
isPlaying = false;
playPosition = 0f;
}
}
private void SelectGeneratedAudioAsset()
{
if (string.IsNullOrEmpty(generatedAudioPath))
return;
UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(generatedAudioPath);
if (obj != null)
{
Selection.activeObject = obj;
EditorGUIUtility.PingObject(obj);
}
}
private void OnGenerationError(string errorMsg)
{
generateStatus = "Generation failed: " + errorMsg;
isGenerating = false;
Repaint();
}
private static class AudioUtil
{
private static readonly Type audioUtilType;
private static readonly System.Reflection.MethodInfo playClipMethod;
private static readonly System.Reflection.MethodInfo stopClipMethod;
private static readonly System.Reflection.MethodInfo setClipSamplePositionMethod;
static AudioUtil()
{
audioUtilType = typeof(AudioImporter).Assembly.GetType("UnityEditor.AudioUtil");
setClipSamplePositionMethod = audioUtilType.GetMethod("SetClipSamplePosition", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic, null, new Type[] { typeof(AudioClip), typeof(int) }, null);
}
public static void PlayClip(AudioClip clip)
{
playClipMethod?.Invoke(null, new object[] { clip });
}
public static void StopClip(AudioClip clip)
{
stopClipMethod?.Invoke(null, new object[] { clip });
}
public static void SetClipSamplePosition(AudioClip clip, int positionSamples)
{
setClipSamplePositionMethod?.Invoke(null, new object[] { clip, positionSamples });
}
}
private void PlayClipAtPosition(AudioClip clip, float timePosition)
{
if (clip == null) return;
int samplePos = Mathf.Clamp((int)(timePosition * clip.frequency), 0, clip.samples - 1);
AudioUtil.SetClipSamplePosition(clip, samplePos);
}
class ACEStepClientGenerationRunner : MonoBehaviour
{
private static ACEStepClientGenerationRunner _instance;
private ACEStepClient client;
public ACEStepClientGenerationRunner(AceStepEditorWindow window)
{
if (_instance == null)
{
GameObject go = new GameObject("ACEStepClientGenerationRunner");
go.hideFlags = HideFlags.HideAndDontSave;
_instance = go.AddComponent<ACEStepClientGenerationRunner>();
}
client = _instance.gameObject.GetComponent<ACEStepClient>();
if (client == null)
client = _instance.gameObject.AddComponent<ACEStepClient>();
}
public void GenerateAudio(ACEStepInput input, Action<ACEStepOutput> onSuccess, Action<string> onError)
{
_instance.StartCoroutine(client.GenerateAudioRoutine(input, onSuccess, onError));
}
}
}
If you'd like me to also resend any other related scripts or explain parts of this, just ask!
give me a product description for this based off its readme
Welcome to AceStep - Unity Bridge, the ultimate tool to bring powerful music
generation right inside your Unity Editor! Whether you're making games,
interactive experiences, or just want to spice up your prototypes with custom
soundtracks, this bridge seamlessly connects Unity with the mighty AceStep AI
music generator.
It makes integrating AI-driven composition effortless, meaning your projects
can have unique, dynamic soundtracks tailored to your needs — no musical expertise
required!
Important File Placement
Copy the 'infer-api-unity.py' server script from the 'Important Files' folder
of this bridge package INTO THE ROOT DIRECTORY of your AceStep install.
Start the Server:
Activate your AceStep Python or Conda environment.
Run the server with:
python infer-api-unity.py
Wait for the server to fully boot up before continuing.
Open AceStep in Unity:
In Unity, go to 'Tools > AceStep' to open the scripts window.
Pro Tip: Dock the scripts window to one side of your screen and dock the
Inspector on the opposite side so you can preview your generated songs easily.
The generated songs will automatically be highlighted in the Inspector.
🎶 Using AceStep - Unity Bridge
Generate songs based on genres, moods, or full lyrics directly inside Unity.
Preview your music instantly in the Editor.
The script automatically highlights generated songs for fast preview/edit.
💡 Practical Usecases
Dynamic Game Soundtracks
Background music that evolves according to gameplay or player actions.
Rapid Prototyping
Quickly test various musical styles and lyrics without external audio tools.
Learning & Experimentation
Explore songwriting, genres, and lyrics to inspire creativity inside Unity.
❗ Notes & Support
AceStep Installation & Setup:
I do not provide installation support for AceStep itself. Please refer to
their official repository documentation.
Server:
Always ensure 'infer-api-unity.py' server is running before attempting music
generation in Unity.
🙏 Thank You!
Thank you so much for choosing AceStep - Unity Bridge!
Happy composing! 🎼✨
Made with 💙 for creative developers and game makers everywhere.
==============================================================================="
With AceStep - Unity Bridge, you can generate songs from genres, moods, or full lyrics right inside the Unity Editor, instantly preview them, and effortlessly incorporate custom soundtracks tailored to your game's design and atmosphere.
Key Features:
Integrated AI Music Generation: Harness the cutting-edge AceStep AI to compose music dynamically without leaving Unity.
Instant Audio Preview: Listen to generated tracks immediately within the Unity Editor for rapid iteration.
Easy Setup & Workflow: Simple server setup with the included infer-api-unity.py script and intuitive Unity window for generation controls.
Flexible Use Cases: Ideal for dynamic game soundtracks, prototyping audio ideas quickly, and exploring creative songwriting techniques without external tools.
Editor Convenience: Automatically highlights generated audio files in the Unity Inspector for quick access and editing.
Who Is It For?
Game developers seeking adaptive or procedurally generated music.
Creators who want to rapidly prototype and test soundtracks within Unity.
Anyone curious about integrating AI-composed music into interactive experiences.
Please note: AceStep installation and running the server are prerequisites. For full setup guidance, refer to the official AceStep repository.
Bring your Unity projects to life with custom, AI-generated music — effortlessly composed, previewed, and tailored exactly as you imagine it.