Hello I have a Unity C# class that I need you to make me an editor window script for, I want it to be able to be found in tools > Seed_VC. I want the window to display a logo from Resources and allow the user to edit all of the parameters inside that window please leave nothing out. And as for the handling of input audio files I want you to handle those as audio clips from unity. I want you to also save the resulting file inside of unity and give the user in the window the ability to select which asset folder to save it in. Please also provide a 'CONVERT' button in the bottom of the window that kicks off the generation ty.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
public class AudioConverter : MonoBehaviour
{
// The user can set this URL to whatever the API endpoint is
public string serverUrl = "http://localhost:8000/convert";
code
Assistant
public int QualityValue = 10;
[Serializable]
public class ConversionResponse
{
public string windows_path;
public string file_path;
}
/// <summary>
/// Converts audio files by uploading them and related parameters to the server URL.
/// </summary>
/// <param name="Vox1_path">Path to source audio file</param>
/// <param name="Vox2_path">Path to reference audio file</param>
public async Task ConvertStuff(string Vox1_path, string Vox2_path)
{
if (!File.Exists(Vox1_path))
{
Debug.LogError("Source file does not exist: " + Vox1_path);
return;
}
if (!File.Exists(Vox2_path))
{
Debug.LogError("Reference file does not exist: " + Vox2_path);
return;
}
byte[] sourceAudioBytes;
byte[] referenceAudioBytes;
try
{
sourceAudioBytes = File.ReadAllBytes(Vox1_path);
referenceAudioBytes = File.ReadAllBytes(Vox2_path);
}
catch (Exception ex)
{
Debug.LogError($"Failed to read audio files: {ex.Message}");
return;
}
List<IMultipartFormSection> formData = new List<IMultipartFormSection>
{
new MultipartFormFileSection("source_file", sourceAudioBytes, "source.wav", "audio/wav"),
new MultipartFormFileSection("reference_file", referenceAudioBytes, "reference.wav", "audio/wav"),
// Server parameters:
new MultipartFormDataSection("diffusion_steps", QualityValue.ToString()),
new MultipartFormDataSection("length_adjust", "1.0"),
new MultipartFormDataSection("inference_cfg_rate", "0.7"),
new MultipartFormDataSection("auto_f0_adjust", "true"),
new MultipartFormDataSection("pitch_shift", "0")
};
UnityWebRequest request = UnityWebRequest.Post(serverUrl, formData);
try
{
var operation = request.SendWebRequest();
while (!operation.isDone)
await Task.Yield();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogError($"Server error: {request.error}");
return;
}
string result = request.downloadHandler.text;
try
{
ConversionResponse conversionResponse = JsonUtility.FromJson<ConversionResponse>(result);
string filePath = conversionResponse.windows_path ?? conversionResponse.file_path;
if (string.IsNullOrEmpty(filePath))
{
Debug.LogError("Server response does not contain 'windows_path' or 'file_path'");
return;
}
Debug.Log("File saved to: " + filePath);
}
catch (Exception ex)
{
Debug.LogError("Failed to parse server response: " + ex.Message);
}
}
catch (Exception ex)
{
Debug.LogError("Error sending request: " + ex.Message);
}
finally
{
request.Dispose();
}
}
}
Sure! I'll create a Unity Editor Window script called SeedVCWindow that will:
Be accessible via the menu Tools > Seed_VC.
Display a logo loaded from Resources (assuming a texture named "seed_vc_logo" is placed inside Assets/Resources).
Allow editing all parameters inside your AudioConverter class, including the server URL, quality value, and audio clips for source and reference.
Let the user select an asset folder to save the resulting file.
Show a CONVERT button at the bottom that triggers the conversion.
Handle the conversion process, reading the audio clip data, sending it as multipart form data to the server, and saving the returned audio file inside the selected folder as a Unity asset.
Note: The AudioConverter MonoBehaviour will be embedded inside the Editor Window for parameter storage but will not actually be attached to any GameObject. The window script will perform the async request inside the editor using Task and UnityWebRequest.
Here's the complete script for the Editor Window:
csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;
using UnityEngine.Networking;
public class SeedVCWindow : EditorWindow
{
private Texture2D logo;
// Parameters (matching AudioConverter class)
private string serverUrl = "http://localhost:8000/convert";
private int qualityValue = 10;
// Audio clips for input
private AudioClip sourceClip;
private AudioClip referenceClip;
// Selected folder to save result
private DefaultAsset saveFolderAsset;
private string saveFolderPath = "Assets/";
// Status message
private string statusMessage;
private bool isConverting = false;
[MenuItem("Tools/Seed_VC")]
private static void ShowWindow()
{
var window = GetWindow<SeedVCWindow>("Seed_VC");
window.minSize = new Vector2(400, 450);
}
private void OnEnable()
{
// Load logo from Resources folder (Assets/Resources/seed_vc_logo.png)
logo = Resources.Load<Texture2D>("seed_vc_logo");
}
private void OnGUI()
{
GUILayout.Space(10);
if (logo != null)
{
var rect = GUILayoutUtility.GetRect(logo.width, logo.height, GUILayout.ExpandWidth(false));
GUI.DrawTexture(rect, logo, ScaleMode.ScaleToFit);
}
else
{
EditorGUILayout.HelpBox("Logo not found in Resources as 'seed_vc_logo'. Please add a PNG named 'seed_vc_logo' to Assets/Resources.", MessageType.Warning);
}
GUILayout.Space(10);
EditorGUILayout.LabelField("Server URL:", EditorStyles.boldLabel);
serverUrl = EditorGUILayout.TextField(serverUrl);
EditorGUILayout.LabelField("Quality Value (diffusion_steps):", EditorStyles.boldLabel);
qualityValue = EditorGUILayout.IntSlider(qualityValue, 1, 100);
GUILayout.Space(10);
EditorGUILayout.LabelField("Source Audio Clip:", EditorStyles.boldLabel);
sourceClip = (AudioClip)EditorGUILayout.ObjectField(sourceClip, typeof(AudioClip), false);
EditorGUILayout.LabelField("Reference Audio Clip:", EditorStyles.boldLabel);
referenceClip = (AudioClip)EditorGUILayout.ObjectField(referenceClip, typeof(AudioClip), false);
GUILayout.Space(10);
EditorGUILayout.LabelField("Save Folder:", EditorStyles.boldLabel);
EditorGUILayout.BeginHorizontal();
saveFolderAsset = (DefaultAsset)EditorGUILayout.ObjectField(saveFolderAsset, typeof(DefaultAsset), false);
if (GUILayout.Button("Select Folder", GUILayout.Width(100)))
{
string selectedPath = EditorUtility.OpenFolderPanel("Select Save Folder", Application.dataPath, "");
if (!string.IsNullOrEmpty(selectedPath))
{
// Convert absolute path to relative Unity project path
if (selectedPath.StartsWith(Application.dataPath))
{
saveFolderPath = "Assets" + selectedPath.Substring(Application.dataPath.Length);
saveFolderAsset = AssetDatabase.LoadAssetAtPath<DefaultAsset>(saveFolderPath);
}
else
{
EditorUtility.DisplayDialog("Invalid Folder", "Selected folder must be inside the Assets directory.", "OK");
}
}
}
EditorGUILayout.EndHorizontal();
GUILayout.Space(15);
GUI.enabled = !isConverting;
if (GUILayout.Button("CONVERT", GUILayout.Height(40)))
{
if (!ValidateInputs())
return;
_ = ConvertAudioFiles();
}
GUI.enabled = true;
GUILayout.Space(10);
EditorGUILayout.HelpBox(statusMessage, MessageType.Info);
}
private bool ValidateInputs()
{
if (string.IsNullOrWhiteSpace(serverUrl))
{
statusMessage = "Server URL cannot be empty.";
return false;
}
if (qualityValue < 1)
{
statusMessage = "Quality value must be greater than 0.";
return false;
}
if (sourceClip == null)
{
statusMessage = "Please assign a Source Audio Clip.";
return false;
}
if (referenceClip == null)
{
statusMessage = "Please assign a Reference Audio Clip.";
return false;
}
if (saveFolderAsset == null || string.IsNullOrEmpty(saveFolderPath))
{
statusMessage = "Please select a save folder inside the Assets directory.";
return false;
}
return true;
}
private async Task ConvertAudioFiles()
{
isConverting = true;
statusMessage = "Reading audio clips and preparing data...";
Repaint();
try
{
// Convert AudioClips to WAV byte arrays
byte[] sourceWavData = AudioClipToWav(sourceClip);
byte[] referenceWavData = AudioClipToWav(referenceClip);
if (sourceWavData == null || referenceWavData == null)
{
statusMessage = "Failed to convert AudioClips to WAV bytes.";
isConverting = false;
Repaint();
return;
}
statusMessage = "Sending data to server...";
Repaint();
var result = await UploadAudioAndConvert(sourceWavData, referenceWavData);
if (!string.IsNullOrEmpty(result))
{
statusMessage = $"Conversion succeeded, saving the file...";
Repaint();
bool saved = SaveFileToAssetFolder(result);
if (saved)
{
statusMessage = "File saved successfully.";
}
else
{
statusMessage = "Failed to save the file as an asset.";
}
}
else
{
statusMessage = "Conversion failed or no file returned.";
}
}
catch (Exception ex)
{
Debug.LogException(ex);
statusMessage = $"An error occurred: {ex.Message}";
}
finally
{
isConverting = false;
Repaint();
}
}
private async Task<string> UploadAudioAndConvert(byte[] sourceAudioBytes, byte[] referenceAudioBytes)
{
List<IMultipartFormSection> formData = new List<IMultipartFormSection>
{
new MultipartFormFileSection("source_file", sourceAudioBytes, "source.wav", "audio/wav"),
new MultipartFormFileSection("reference_file", referenceAudioBytes, "reference.wav", "audio/wav"),
// Server parameters:
new MultipartFormDataSection("diffusion_steps", qualityValue.ToString()),
new MultipartFormDataSection("length_adjust", "1.0"),
new MultipartFormDataSection("inference_cfg_rate", "0.7"),
new MultipartFormDataSection("auto_f0_adjust", "true"),
new MultipartFormDataSection("pitch_shift", "0")
};
using (UnityWebRequest request = UnityWebRequest.Post(serverUrl, formData))
{
var operation = request.SendWebRequest();
while (!operation.isDone)
await Task.Yield();
#if UNITY_2020_1_OR_NEWER
if (request.result != UnityWebRequest.Result.Success)
#else
if (request.isNetworkError || request.isHttpError)
#endif
{
statusMessage = $"Server error: {request.error}";
return null;
}
var textResult = request.downloadHandler.text;
if (string.IsNullOrWhiteSpace(textResult))
{
statusMessage = "Server returned an empty response.";
return null;
}
try
{
ConversionResponse response = JsonUtility.FromJson<ConversionResponse>(textResult);
string filePath = response.windows_path ?? response.file_path;
if (string.IsNullOrEmpty(filePath))
{
statusMessage = "Server response does not contain a valid file path.";
return null;
}
// Read the returned file bytes, assuming server returns a path accessible on local machine or network
if (!File.Exists(filePath))
{
statusMessage = $"Returned file does not exist on disk: {filePath}";
return null;
}
byte[] convertedFileBytes = File.ReadAllBytes(filePath);
// Return this byte array as Base64 string for saving later
return Convert.ToBase64String(convertedFileBytes);
}
catch (Exception ex)
{
statusMessage = "Failed to parse server response: " + ex.Message;
return null;
}
}
}
private bool SaveFileToAssetFolder(string base64FileData)
{
try
{
byte[] fileBytes = Convert.FromBase64String(base64FileData);
string fileName = $"converted_{DateTime.Now:yyyyMMdd_HHmmss}.wav";
string fullPath = Path.Combine(saveFolderPath, fileName);
string absolutePath = Path.Combine(Application.dataPath.Substring(0, Application.dataPath.Length - 6), fullPath);
File.WriteAllBytes(absolutePath, fileBytes);
// Refresh AssetDatabase so the file shows up
AssetDatabase.Refresh();
// Optionally, import it as an AudioClip asset
AudioImporter importer = (AudioImporter)AssetImporter.GetAtPath(fullPath);
if (importer != null)
{
importer.loadInBackground = false;
importer.SaveAndReimport();
}
return true;
}
catch (Exception ex)
{
Debug.LogError("Failed to save file: " + ex);
return false;
}
}
/// <summary>
/// Converts an AudioClip to WAV format byte array.
/// Only supports PCM 16-bit samples.
/// This method uses the Unity Wav utility approach.
/// </summary>
private byte[] AudioClipToWav(AudioClip clip)
{
if (clip == null)
return null;
float[] samples = new float[clip.samples * clip.channels];
clip.GetData(samples, 0);
byte[] wavData = ConvertAudioClipDataToWav(samples, clip.channels, clip.frequency);
return wavData;
}
/// <summary>
/// Converts float samples to WAV byte array (PCM 16-bit)
/// Adapted from https://gist.github.com/darktable/2317063
/// </summary>
private byte[] ConvertAudioClipDataToWav(float[] samples, int channels, int sampleRate)
{
MemoryStream stream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(stream);
int sampleCount = samples.Length;
// RIFF header
writer.Write(System.Text.Encoding.UTF8.GetBytes("RIFF"));
writer.Write(36 + sampleCount * 2); // file size minus 8 bytes
writer.Write(System.Text.Encoding.UTF8.GetBytes("WAVE"));
// fmt chunk
writer.Write(System.Text.Encoding.UTF8.GetBytes("fmt "));
writer.Write(16); // Sub-chunk size
writer.Write((short)1); // Audio format = PCM
writer.Write((short)channels);
writer.Write(sampleRate);
writer.Write(sampleRate * channels * 2); // Byte rate
writer.Write((short)(channels * 2)); // Block align
writer.Write((short)16); // Bits per sample
// data chunk
writer.Write(System.Text.Encoding.UTF8.GetBytes("data"));
writer.Write(sampleCount * 2); // Subchunk2Size
// Write sample data
short[] intData = new short[sampleCount];
for (int i = 0; i < sampleCount; i++)
{
float sample = Mathf.Clamp(samples[i], -1f, 1f);
intData[i] = (short)(sample * short.MaxValue);
}
for (int i = 0; i < intData.Length; i++)
{
writer.Write(intData[i]);
}
writer.Flush();
writer.Close();
return stream.ToArray();
}
// Matching your ConversionResponse class
[Serializable]
private class ConversionResponse
{
public string windows_path;
public string file_path;
}
}
Instructions:
Save this script in your project under Assets/Editor/SeedVCWindow.cs.
Add a logo PNG file named seed_vc_logo.png inside Assets/Resources/.
Open the window under Tools > Seed_VC.
Assign the source & reference audio clips inside the window.
Select a folder in your Assets/ directory where to save the converted audio file.
Click CONVERT.
Notes:
The script converts the assigned audio clips to WAV format (PCM 16-bit) before sending them to your API.
The API is expected to return a JSON response containing either "windows_path" or "file_path" fields pointing to the location where the converted WAV file is saved.
The script reads that local file and saves it as an asset in the selected folder.
The folder chooser only allows folders inside the Assets directory to ensure Unity asset consistency.
The CONVERT button is disabled during conversion.
Status messages shown at the bottom will give feedback for the current operation.
If you want me to integrate your existing AudioConverter MonoBehaviour directly or want me to split this further into runtime and editor classes, just ask!