I need to change how wav files audio clips are worked with on my script based off this new asset I imported that handles this process better than we did

'converter code'
using UnityEngine;
using System.Collections.Generic;

/* This static class is developped to convert a wav file (from a byte array) into a
 * UnityEngine AudioClip to be played dynamically.
 * 
 * The other function allows your application to pick any AudioClip with valid data
 * and convert its content into a wav file (to a byte array).
 * 
 * The way you read or save the files is up to you (depending on the platform).
 * 
 * eToile recommends using FileManagement to read and save files (OWP is already integrated):
 * https://assetstore.unity.com/packages/slug/67183
 * 
 * V1.1:
 * New feature: Automatic detection of valid headers for non WAV files.
 * 
 * V1.2:
 * BugFix: Failing when reading empty or corrupted files.
 * 
 * v1.3:
 * BugFix: Workaround to avoid AudioClip generating incorrect length (fix for loopable clips).
 * 
 * v1.4:
 * NewFeature: 24bit WAV compatibility.
 * NewFeature: 32bit WAV compatibility.
 * NewFeature: Simple method to combine AudioClips.
 * 
 * v1.5:
 * BugFix: Multi-channel AudioClip incomplete when saving.
 * 
 * v1.6:
 * NewFeature: Stereo to mono and mono to stereo resampling.
 * 
 * v1.7:
 * NewFeature: Main class added to eToile namespace.
 */

namespace eToile
{
    public static class OpenWavParser
    {
        /// <summary>Available audio resolutions</summary>
        public enum Resolution
        {
            _16bit = 16,
            _24bit = 24,
            _32bit = 32
        }

        ///<summary>Check if the provided file is a valid PCM file</summary
        public static bool IsWAVFile(byte[] wavFile)
        {
            if (wavFile.Length > 12)
            {
                byte[] data = new byte[4];
                System.Buffer.BlockCopy(wavFile, 0, data, 0, data.Length);
                string _chunkID = ByteArrayToString(data);
                System.Buffer.BlockCopy(wavFile, 8, data, 0, data.Length);
                string _format = ByteArrayToString(data);
                return (_chunkID == "RIFF" && _format == "WAVE");
            }
            return false;
        }
        /// <summary>Load audio file into AudioClip</summary>
        public static AudioClip ByteArrayToAudioClip(byte[] wavFile, string name = "", bool stream = false)
        {
            /* WAV file format:
             * 
             * size - Name              - (index)   Description.
             * 
             * 4    - ChunkID           - (0)       "RIFF"
             * 4    - ChunkSize         - (4)       file size minus 8 (RIFF(4) + ChunkSize(4)).
             * 4    - Format            - (8)       "WAVE"
             * 
             * 4    - Subchunk1ID       - (12)      "fmt "
             * 4    - Subchunk1Size     - (16)      16 bytes for PCM (bytes 20 to 36)
             * 2    - AudioFormat       - (20)      1 for PCM (other values implies some compression).
             * 2    - NumChannels       - (22)      Mono = 1, Stereo = 2, etc.
             * 4    - SampleRate        - (24)      8000, 22050, 44100, etc.
             * 4    - ByteRate          - (28)      == SampleRate * NumChannels * (BitsPerSample/8)
             * 2    - BlockAlign        - (32)      == NumChannels * (BitsPerSample/8)
             * 2    - BitsPerSample     - (34)      8 bits = 8, 16 bits = 16, etc.
             * (Here goes the extra data pointed by Subchunk1Size > 16)
             * 
             * 4    - Subchunk2ID       - (36)      "data"
             * 4    - Subchunk2Size     - (40)
             * Subchunk2Size (Data)     - (44)
             */

            // Check if the provided file is a valid PCM file:
            if (IsWAVFile(wavFile))
            {
                //int _chunkSize = System.BitConverter.ToInt32(wavFile, 4);                         // Not used.
                int _subchunk1Size = System.BitConverter.ToInt32(wavFile, 16);
                int _audioFormat = System.BitConverter.ToInt16(wavFile, 20);
                int _numChannels = System.BitConverter.ToInt16(wavFile, 22);
                int _sampleRate = System.BitConverter.ToInt32(wavFile, 24);
                //int _byteRate = System.BitConverter.ToInt32(wavFile, 28);                         // Not used.
                //int _blockAlign = System.BitConverter.ToInt16(wavFile, 32);                       // Not used.
                Resolution _bitsPerSample = (Resolution)System.BitConverter.ToInt16(wavFile, 34);
                // PCM WAV method:
                if (_audioFormat == 1)
                {
                    // Find where data starts:
                    int _dataIndex = 20 + _subchunk1Size;
                    for (int i = _dataIndex; i < wavFile.Length; i++)
                    {
                        if (wavFile[i] == 'd' && wavFile[i + 1] == 'a' && wavFile[i + 2] == 't' && wavFile[i + 3] == 'a')
                        {
                            _dataIndex = i + 4;     // "data" string size = 4
                            break;
                        }
                    }
                    // Data parameters:
                    int _subchunk2Size = System.BitConverter.ToInt32(wavFile, _dataIndex);          // Data size (Subchunk2Size).
                    _dataIndex += 4;                                                                // Subchunk2Size = 4
                    int _sampleSize = (int)_bitsPerSample / 8;                                      // Size of a sample.
                    int _sampleCount = _subchunk2Size / _sampleSize;                                // How many samples into data.
                                                                                                    // Data conversion:
                    float[] _audioBuffer = new float[_sampleCount];                                 // Size for all available channels.
                    for (int i = 0; i < _sampleCount; i++)
                    {
                        int sampleIndex = _dataIndex + i * _sampleSize;
                        int intSample = 0;
                        float sample = 0;
                        switch (_bitsPerSample)
                        {
                            case Resolution._16bit:
                                intSample = System.BitConverter.ToInt16(wavFile, sampleIndex);
                                sample = intSample / 32767f;
                                break;
                            case Resolution._24bit:
                                intSample = System.BitConverter.ToInt32(new byte[] { 0, wavFile[sampleIndex], wavFile[sampleIndex + 1], wavFile[sampleIndex + 2] }, 0) >> 8;
                                sample = intSample / 8388607f;
                                break;
                            case Resolution._32bit:
                                intSample = System.BitConverter.ToInt32(wavFile, sampleIndex);
                                sample = intSample / 2147483647f;
                                break;
                        }
                        _audioBuffer[i] = sample;
                    }
                    // Create the AudioClip:
                    AudioClip audioClip = AudioClip.Create(name, _sampleCount / _numChannels, _numChannels, _sampleRate, stream);
                    audioClip.SetData(_audioBuffer, 0);
                    return audioClip;
                }
                else
                {
                    Debug.LogError("[OpenWavParser.ByteArrayToAudioClip] Compressed wav format not supported.");
                    return null;
                }
            }
            else
            {
                Debug.LogError("[OpenWavParser.ByteArrayToAudioClip] Format not supported.");
                return null;
            }
        }
        ///<summary>Returns a wav file from any AudioClip</summary
        public static byte[] AudioClipToByteArray(AudioClip clip, Resolution res = Resolution._16bit)
        {
            // Clip content:
            float[] samples = new float[clip.samples * clip.channels];
            clip.GetData(samples, 0);                                                               // The audio data in samples.
                                                                                                    // Write all data to byte array:
            List<byte> wavFile = new List<byte>();
            // RIFF header:
            int size = (int)res / 8;
            wavFile.AddRange(new byte[] { (byte)'R', (byte)'I', (byte)'F', (byte)'F' });            // "RIFF"
            wavFile.AddRange(System.BitConverter.GetBytes(samples.Length * size + 44 - 8));         // ChunkSize
            wavFile.AddRange(new byte[] { (byte)'W', (byte)'A', (byte)'V', (byte)'E' });            // "WAVE"
            wavFile.AddRange(new byte[] { (byte)'f', (byte)'m', (byte)'t', (byte)' ' });            // "fmt "
            wavFile.AddRange(System.BitConverter.GetBytes(16));                                     // Subchunk1Size (the next 16 bytes)
            wavFile.AddRange(System.BitConverter.GetBytes((ushort)1));                              // AudioFormat (1 for PCM)
            wavFile.AddRange(System.BitConverter.GetBytes((ushort)clip.channels));                  // NumChannels
            wavFile.AddRange(System.BitConverter.GetBytes(clip.frequency));                         // SampleRate
            wavFile.AddRange(System.BitConverter.GetBytes(clip.frequency * clip.channels * size));  // ByteRate
            wavFile.AddRange(System.BitConverter.GetBytes((ushort)(clip.channels * size)));         // BlockAlign
            wavFile.AddRange(System.BitConverter.GetBytes((ushort)res));                            // BitsPerSample
            wavFile.AddRange(new byte[] { (byte)'d', (byte)'a', (byte)'t', (byte)'a' });            // "data"
            wavFile.AddRange(System.BitConverter.GetBytes(samples.Length * size));                  // Subchunk2Size
                                                                                                    // Add the audio data in bytes:
            for (int i = 0; i < samples.Length; i++)
            {
                switch (res)
                {
                    case Resolution._16bit:
                        short sample16 = (short)(samples[i] * 32767f);
                        wavFile.AddRange(System.BitConverter.GetBytes(sample16));
                        break;
                    case Resolution._24bit:
                        int sample24 = Mathf.FloorToInt(samples[i] * 8388607);
                        byte[] data = System.BitConverter.GetBytes(sample24);
                        wavFile.AddRange(new byte[] { data[0], data[1], data[2] });
                        break;
                    case Resolution._32bit:
                        int sample32 = (int)(samples[i] * 2147483647f);
                        wavFile.AddRange(System.BitConverter.GetBytes(sample32));
                        break;
                }
            }
            // Return the byte array to be saved:
            return wavFile.ToArray();
        }

        ///<summary>Converts to 8 bit characters only</summary>
        static string ByteArrayToString(byte[] content)
        {
            char[] chars = new char[content.Length];
            content.CopyTo(chars, 0);
            return new string(chars);
        }

        ///<summary>Combines all AudioClip from the array</summary>
        public static AudioClip Combine(AudioClip[] clips)
        {
            if (clips == null || clips.Length == 0)
                return null;

            int length = 0;
            for (int i = 0; i < clips.Length; i++)
            {
                if (clips[i] != null)
                    length += clips[i].samples * clips[i].channels;
            }

            float[] data = new float[length];
            length = 0;
            for (int i = 0; i < clips.Length; i++)
            {
                if (clips[i] != null)
                {
                    float[] buffer = new float[clips[i].samples * clips[i].channels];
                    clips[i].GetData(buffer, 0);
                    buffer.CopyTo(data, length);
                    length += buffer.Length;
                }
            }

            AudioClip audioClip = null;
            if (length > 0)
            {
                audioClip = AudioClip.Create("AudioClip", length / 2, 2, 44100, false);
                audioClip.SetData(data, 0);
            }
            return audioClip;
        }
        ///<summary>Resamples a stereo clip to mono (Mixes both channels)</summary>
        public static AudioClip StereoToMono(AudioClip stereoClip, bool stream = false)
        {
            // Get stereo data:
            float[] _audioStereo = new float[stereoClip.samples * stereoClip.channels];
            stereoClip.GetData(_audioStereo, 0);
            // Mxx to mono data:
            float[] _audioBuffer = new float[stereoClip.samples];
            for (int s = 0; s < _audioBuffer.Length; s++)
            {
                _audioBuffer[s] = (float)((double)_audioStereo[s * 2] + _audioStereo[s * 2 + 1]) / 2f;
            }
            AudioClip audioClip = AudioClip.Create(stereoClip.name, _audioBuffer.Length, 1, stereoClip.frequency, stream);
            audioClip.SetData(_audioBuffer, 0);
            return audioClip;
        }
        ///<summary>Resamples a mono clip to stereo (Copies the mono channel)</summary>
        public static AudioClip MonoToStereo(AudioClip monoClip, bool stream = false)
        {
            // Get mono data:
            float[] _audioMono = new float[monoClip.samples];
            monoClip.GetData(_audioMono, 0);
            // Convert to stereo data:
            float[] _audioBuffer = new float[monoClip.samples * 2];
            for (int s = 0; s < _audioBuffer.Length; s += 2)
            {
                _audioBuffer[s] = _audioMono[s / 2];
                _audioBuffer[s + 1] = _audioMono[s / 2];
            }
            AudioClip audioClip = AudioClip.Create(monoClip.name, monoClip.samples, 2, monoClip.frequency, stream);
            audioClip.SetData(_audioBuffer, 0);
            return audioClip;
        }
    }
}

my scripts that need the update

using System;
using System.IO;
using UnityEngine;
using UnityEngine.EventSystems;
using System.Text;

#if UNITY_ANDROID
using UnityEngine.Android;
#endif

public class AudioRecorderWithButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    [Tooltip("Output file folder - if empty, defaults to persistentDataPath/AudioOut")]
    public string audioFileOutPath;

    private AudioClip recordingClip;
    private bool isRecording = false;
    private string microphoneDevice;
    private int sampleRate = 16000;

    public OllamaInfer OIF;
    public FastAPIAudioTranscriber transcriber;

    private void Start()
    {
        // Default output folder if not set
        if (string.IsNullOrEmpty(audioFileOutPath))
        {
            audioFileOutPath = Path.Combine(Application.persistentDataPath, "AudioOut");
        }

#if UNITY_ANDROID
        if (!Permission.HasUserAuthorizedPermission(Permission.Microphone))
        {
            Permission.RequestUserPermission(Permission.Microphone);
        }
#endif
    }

    // Called when pointer (mouse or touch) presses down on this UI element (button)
    public void OnPointerDown(PointerEventData eventData)
    {
        if (transcriber != null)
            transcriber.AgentTalkMode = true;

        Debug.Log("Button pressed - starting recording...");
        StartRecording();
    }

    // Called when pointer (mouse or touch) releases on this UI element (button)
    public void OnPointerUp(PointerEventData eventData)
    {
        Debug.Log("Button released - stopping recording...");
        StopAndSaveRecording();
    }

    public void StartRecording()
    {
#if UNITY_ANDROID
        if (!Permission.HasUserAuthorizedPermission(Permission.Microphone))
        {
            Debug.LogWarning("Microphone permission not granted.");
            return;
        }
#endif

        microphoneDevice = Microphone.devices.Length > 0 ? Microphone.devices[0] : null;
        if (microphoneDevice == null)
        {
            Debug.LogError("No microphone devices found.");
            return;
        }

        Debug.Log("Starting recording using device: " + microphoneDevice);

        // Start a max 300 seconds recording; looping false
        recordingClip = Microphone.Start(microphoneDevice, false, 300, sampleRate);

        if (recordingClip == null)
        {
            Debug.LogError("Failed to start recording.");
            return;
        }

        isRecording = true;
    }

    public void StopAndSaveRecording()
    {
        if (!isRecording)
        {
            Debug.LogWarning("StopAndSaveRecording called but not currently recording.");
            return;
        }

        // Get actual recorded length BEFORE ending the recording!
        int position = Microphone.GetPosition(microphoneDevice);
        if (position <= 0)
        {
            Debug.LogWarning("Recording too short or failed.");
            isRecording = false;
            recordingClip = null;
            return;
        }

        if (Microphone.IsRecording(microphoneDevice))
        {
            Microphone.End(microphoneDevice);
            Debug.Log("Microphone recording stopped.");
        }

        if (recordingClip == null)
        {
            Debug.LogWarning("No recording clip available to save.");
            isRecording = false;
            return;
        }

        float[] samples = new float[recordingClip.samples * recordingClip.channels];
        recordingClip.GetData(samples, 0);

        // Trim samples array to actual recorded data length
        float[] trimmedSamples = new float[position * recordingClip.channels];
        Array.Copy(samples, 0, trimmedSamples, 0, trimmedSamples.Length);

        // Create a new trimmed AudioClip
        AudioClip trimmedClip = AudioClip.Create("trimmed", position, recordingClip.channels, recordingClip.frequency, false);
        trimmedClip.SetData(trimmedSamples, 0);

        // Replace original clip with trimmed clip for saving
        recordingClip = trimmedClip;

        try
        {
            if (!Directory.Exists(audioFileOutPath))
            {
                Directory.CreateDirectory(audioFileOutPath);
            }
        }
        catch (Exception e)
        {
            Debug.LogError("Failed to create directory: " + e);
            isRecording = false;
            return;
        }

        string filepath = Path.Combine(audioFileOutPath, "Recording.wav");

        if (File.Exists(filepath))
        {
            try
            {
                File.Delete(filepath);
            }
            catch (Exception e)
            {
                Debug.LogError("Failed to delete existing recording file: " + e);
                isRecording = false;
                return;
            }
        }

        bool success = SaveWavFile(recordingClip, filepath);
        if (success)
        {
            FileInfo fi = new FileInfo(filepath);
            Debug.Log($"Saved recording to: {filepath}, file size: {fi.Length} bytes");

            if (transcriber != null)
            {
                transcriber.AgentTalkMode = true;
                transcriber.audioFilePath = filepath;
                transcriber.StartTranscriptionAsync();
            }
            else
            {
                Debug.LogWarning("Transcriber reference not set.");
            }
        }
        else
        {
            Debug.LogError("Failed to save WAV file.");
        }

        isRecording = false;
        recordingClip = null;
    }

    /// <summary>
    /// Saves an AudioClip to a WAV file.
    /// Note: AudioClip must be PCM, frequency should be the same as recorded.
    /// </summary>
    /// <param name="clip">AudioClip to save</param>
    /// <param name="filepath">Full path to save WAV</param>
    /// <returns>True if success</returns>
    public bool SaveWavFile(AudioClip clip, string filepath)
    {
        if (clip == null)
        {
            Debug.LogError("SaveWavFile called with null AudioClip");
            return false;
        }

        try
        {
            using (FileStream fileStream = CreateEmptyWav(filepath))
            {
                ConvertAndWrite(fileStream, clip);
                WriteHeader(fileStream, clip);
            }
            return true;
        }
        catch (Exception e)
        {
            Debug.LogError($"Exception during WAV save: {e}");
            return false;
        }
    }

    private FileStream CreateEmptyWav(string filepath)
    {
        var fileStream = new FileStream(filepath, FileMode.Create);
        // Write a placeholder 44 byte WAV header (will rewrite later)
        byte[] emptyHeader = new byte[44];
        fileStream.Write(emptyHeader, 0, emptyHeader.Length);
        return fileStream;
    }

    private void ConvertAndWrite(FileStream fileStream, AudioClip clip)
    {
        float[] samples = new float[clip.samples * clip.channels];
        clip.GetData(samples, 0);

        short[] intData = new short[samples.Length];
        byte[] bytesData = new byte[samples.Length * 2];

        // Convert float samples to Int16 PCM
        const float rescaleFactor = 32767f;

        for (int i = 0; i < samples.Length; i++)
        {
            float sample = Mathf.Clamp(samples[i], -1f, 1f);
            intData[i] = (short)(sample * rescaleFactor);
            byte[] byteArr = BitConverter.GetBytes(intData[i]);
            byteArr.CopyTo(bytesData, i * 2);
        }

        fileStream.Write(bytesData, 0, bytesData.Length);
    }

    private void WriteHeader(FileStream fileStream, AudioClip clip)
    {
        int hz = clip.frequency;
        int channels = clip.channels;
        int samples = clip.samples;

        fileStream.Seek(0, SeekOrigin.Begin);

        byte[] riff = Encoding.ASCII.GetBytes("RIFF");
        fileStream.Write(riff, 0, 4);

        byte[] chunkSize = BitConverter.GetBytes((int)(fileStream.Length - 8));
        fileStream.Write(chunkSize, 0, 4);

        byte[] wave = Encoding.ASCII.GetBytes("WAVE");
        fileStream.Write(wave, 0, 4);

        byte[] fmt = Encoding.ASCII.GetBytes("fmt ");
        fileStream.Write(fmt, 0, 4);

        byte[] subChunk1 = BitConverter.GetBytes(16);
        fileStream.Write(subChunk1, 0, 4);

        ushort audioFormat = 1; // PCM
        byte[] audioFormatBytes = BitConverter.GetBytes(audioFormat);
        fileStream.Write(audioFormatBytes, 0, 2);

        byte[] numChannels = BitConverter.GetBytes((ushort)channels);
        fileStream.Write(numChannels, 0, 2);

        byte[] sampleRate = BitConverter.GetBytes(hz);
        fileStream.Write(sampleRate, 0, 4);

        byte[] byteRate = BitConverter.GetBytes(hz * channels * 2);
        fileStream.Write(byteRate, 0, 4);

        ushort blockAlign = (ushort)(channels * 2);
        byte[] blockAlignBytes = BitConverter.GetBytes(blockAlign);
        fileStream.Write(blockAlignBytes, 0, 2);

        ushort bitsPerSample = 16;
        byte[] bitsPerSampleBytes = BitConverter.GetBytes(bitsPerSample);
        fileStream.Write(bitsPerSampleBytes, 0, 2);

        byte[] dataString = Encoding.ASCII.GetBytes("data");
        fileStream.Write(dataString, 0, 4);

        int subChunk2 = samples * channels * 2;
        byte[] subChunk2Bytes = BitConverter.GetBytes(subChunk2);
        fileStream.Write(subChunk2Bytes, 0, 4);
    }

    // Optional helper for sanitizing file/folder names if you want to organize by agent
    private string SanitizeFileName(string filename)
    {
        if (string.IsNullOrEmpty(filename))
            return "UnknownAgent";

        foreach (char c in Path.GetInvalidFileNameChars())
            filename = filename.Replace(c.ToString(), "");

        return filename;
    }
}

using System.Collections.Generic;
using System.IO;
using TMPro;
using UnityEngine;
using Michsky.UI.Reach;

public class LOADSAVE : MonoBehaviour
{
    public string FinalPath;
    public TMP_InputField AgentName;
    public TMP_InputField AgentPerson;
    public Michsky.UI.Reach.Dropdown SelectedAgent;
    public string RefVoice;
    public TMP_InputField Transcription;
    public FastAPIAudioTranscriber TRANSCRIBER;
    public string baseFolder = string.Empty;
    public string agentFolderName = string.Empty;
    public string agentFolderPath = string.Empty;

    private string wavFileType;

    private AudioClip recordingClip;
    private bool isRecording = false;
    private const int recordingFreq = 44100; // common freq for WAV
    private float maxRecordingDuration = 60f; // max seconds for recording

    void Start()
    {
        // Setup persistent base folder + extension for wav files
        baseFolder = Path.Combine(Application.persistentDataPath, "Agent Presets");

        // NativeFilePicker wants extension *without* the dot:
        wavFileType = NativeFilePicker.ConvertExtensionToFileType("wav");
    }

    public void LoadFileVoice()
    {
        NativeFilePicker.PickFile((path) =>
        {
            if (string.IsNullOrEmpty(path))
            {
                Debug.Log("Operation cancelled");
                return;
            }

            Debug.Log($"Selected file: {path}");
            FinalPath = path;
            RefVoice = path;

            try
            {
                string agentNameText = SanitizeFileName(string.IsNullOrEmpty(AgentName.text) ? "DefaultAgent" : AgentName.text);

                string baseFolderPath = Path.Combine(Application.persistentDataPath, "Agent Presets");
                string agentFolder = Path.Combine(baseFolderPath, agentNameText);

                if (!Directory.Exists(agentFolder))
                    Directory.CreateDirectory(agentFolder);

                string destFilePath = Path.Combine(agentFolder, "Agent_Voice.wav");

                // Copy the selected WAV file to agent folder
                File.Copy(path, destFilePath, true);

                Debug.Log($"Voice file copied to: {destFilePath}");

                TRANSCRIBER.audioFilePath = destFilePath;
            }
            catch (System.Exception ex)
            {
                Debug.LogError($"Failed to copy voice file: {ex.Message}");
            }

        }, new string[] { wavFileType });
    }

    /// <summary>
    /// Save a file from a given path to a user selectable export location.
    /// </summary>
    /// <param name="filePath">The full path of the file to be exported</param>
    public void SaveFile(string filePath)
    {
        if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
        {
            Debug.LogError("SaveFile: Input file path is invalid or file does not exist");
            return;
        }

        string tempPath = Path.Combine(Application.temporaryCachePath, "test.wav");

        try
        {
            byte[] bytes = File.ReadAllBytes(filePath);
            File.WriteAllBytes(tempPath, bytes);

            NativeFilePicker.ExportFile(tempPath, (success) =>
            {
                Debug.Log("File export success: " + success);
            });
        }
        catch (System.Exception ex)
        {
            Debug.LogError($"SaveFile: Failed to export file: {ex}");
        }
    }

    public void SaveAgentTranscription()
    {
        try
        {
            string agentNameText = SanitizeFileName(string.IsNullOrEmpty(AgentName.text) ? "DefaultAgent" : AgentName.text);

            string baseFolderPath = Path.Combine(Application.persistentDataPath, "Agent Presets");
            if (!Directory.Exists(baseFolderPath))
                Directory.CreateDirectory(baseFolderPath);

            string agentFolder = Path.Combine(baseFolderPath, agentNameText);
            if (!Directory.Exists(agentFolder))
                Directory.CreateDirectory(agentFolder);

            string filePath = Path.Combine(agentFolder, "Agent_Transcription.txt");

            File.WriteAllText(filePath, Transcription.text);

            Debug.Log($"Transcription saved successfully at: {filePath}");
        }
        catch (System.Exception ex)
        {
            Debug.LogError($"Failed to save transcription: {ex}");
        }
    }

    public void SaveFileAgent()
    {
        try
        {
            string agentNameText = SanitizeFileName(string.IsNullOrEmpty(AgentName.text) ? "DefaultAgent" : AgentName.text);

            string baseFolderPath = Path.Combine(Application.persistentDataPath, "Agent Presets");
            if (!Directory.Exists(baseFolderPath))
                Directory.CreateDirectory(baseFolderPath);

            string agentFolder = Path.Combine(baseFolderPath, agentNameText);
            if (!Directory.Exists(agentFolder))
                Directory.CreateDirectory(agentFolder);

            string fileName = SanitizeFileName(agentNameText + "_INFO") + ".txt";
            string filePath = Path.Combine(agentFolder, fileName);

            List<string> lines = new List<string>
            {
                AgentName.text,
                AgentPerson.text,
            };

            File.WriteAllLines(filePath, lines);

            Debug.Log($"Agent info file saved successfully at: {filePath}");
        }
        catch (System.Exception ex)
        {
            Debug.LogError($"Failed to save file: {ex}");
        }
    }

    public void LoadAgentsInDrop()
    {
        string baseFolderPath = Path.Combine(Application.persistentDataPath, "Agent Presets");

        if (!Directory.Exists(baseFolderPath))
        {
            Debug.LogWarning($"Agent Presets folder does not exist at: {baseFolderPath}");
            return;
        }

        SelectedAgent.items.Clear();

        string[] agentFolders = Directory.GetDirectories(baseFolderPath);

        if (agentFolders.Length == 0)
        {
            Debug.Log("No agent folders found in Agent Presets.");
            return;
        }

        foreach (string folderPath in agentFolders)
        {
            string folderName = Path.GetFileName(folderPath);
            SelectedAgent.CreateNewItem(folderName);
        }
    }

    public void RecordAgentVoice()
    {
        if (!isRecording)
        {
            if (string.IsNullOrEmpty(AgentName.text))
            {
                Debug.LogWarning("AgentName is empty. Please enter a valid agent name before recording.");
                return;
            }

            Debug.Log("Started recording...");

            recordingClip = Microphone.Start(null, false, (int)maxRecordingDuration, recordingFreq);
            isRecording = true;
        }
        else
        {
            if (!Microphone.IsRecording(null))
            {
                Debug.LogWarning("Microphone is not recording currently.");
                isRecording = false;
                return;
            }

            int length = Microphone.GetPosition(null);
            Microphone.End(null);

            if (length <= 0)
            {
                Debug.LogError("Recorded audio length is 0.");
                isRecording = false;
                return;
            }

            // Correct sample trimming: get samples only for recorded length
            float[] samples = new float[length * recordingClip.channels];
            recordingClip.GetData(samples, 0);

            AudioClip clippedClip = AudioClip.Create(recordingClip.name, length, recordingClip.channels, recordingClip.frequency, false);
            clippedClip.SetData(samples, 0);

            try
            {
                string baseFolderPath = Path.Combine(Application.persistentDataPath, "Agent Presets");
                string agentFolderName = SanitizeFileName(AgentName.text);
                string agentFolderPath = Path.Combine(baseFolderPath, agentFolderName);

                if (!Directory.Exists(agentFolderPath))
                    Directory.CreateDirectory(agentFolderPath);

                string filePath = Path.Combine(agentFolderPath, "Agent_Voice.wav");

                // Use fixed WAV save method
                SaveWavFile(filePath, clippedClip);

                Debug.Log($"Recording saved to: {filePath}");
            }
            catch (System.Exception ex)
            {
                Debug.LogError($"Failed to save recorded voice: {ex.Message}");
            }

            isRecording = false;
        }
    }

    /// <summary>
    /// Save AudioClip as a proper WAV file using safe, tested conversion and header writing
    /// </summary>
    private void SaveWavFile(string filePath, AudioClip clip)
    {
        if (clip == null)
        {
            Debug.LogError("SaveWavFile: AudioClip is null!");
            return;
        }

        int sampleCount = clip.samples * clip.channels;
        float[] samples = new float[sampleCount];
        clip.GetData(samples, 0);

        int hz = clip.frequency;
        short channels = (short)clip.channels;

        // Convert float samples [-1.0f, 1.0f] to 16-bit PCM data
        byte[] pcmData = new byte[sampleCount * 2]; // 2 bytes per sample for 16-bit

        int pcmIndex = 0;
        for (int i = 0; i < sampleCount; i++)
        {
            short intSample = (short)(Mathf.Clamp(samples[i], -1f, 1f) * short.MaxValue);
            pcmData[pcmIndex++] = (byte)(intSample & 0xFF);
            pcmData[pcmIndex++] = (byte)((intSample >> 8) & 0xFF);
        }

        using (var fileStream = new FileStream(filePath, FileMode.Create))
        using (var writer = new BinaryWriter(fileStream))
        {
            // RIFF header
            writer.Write(System.Text.Encoding.UTF8.GetBytes("RIFF"));
            writer.Write(36 + pcmData.Length); // Chunk size
            writer.Write(System.Text.Encoding.UTF8.GetBytes("WAVE"));

            // fmt subchunk
            writer.Write(System.Text.Encoding.UTF8.GetBytes("fmt "));
            writer.Write(16); // Subchunk1Size for PCM
            writer.Write((short)1); // AudioFormat PCM = 1
            writer.Write(channels);
            writer.Write(hz);
            writer.Write(hz * channels * 2); // Byte rate = SampleRate * NumChannels * BitsPerSample/8
            writer.Write((short)(channels * 2)); // Block align = NumChannels * BitsPerSample/8
            writer.Write((short)16); // Bits per sample

            // data subchunk
            writer.Write(System.Text.Encoding.UTF8.GetBytes("data"));
            writer.Write(pcmData.Length);
            writer.Write(pcmData);
        }

        Debug.Log($"WAV file saved to: {filePath}");
    }

    /// <summary>
    /// Remove invalid characters from filename string
    /// </summary>
    private string SanitizeFileName(string filename)
    {
        foreach (char c in Path.GetInvalidFileNameChars())
            filename = filename.Replace(c.ToString(), "");
        return filename;
    }
}

using UnityEngine;
using Michsky.UI.Reach;
using System.IO;
using System;
using UnityEngine.UI;

public class InjectReqs : MonoBehaviour
{
    public TTSClientRunner ttsClientRunner;
    public Michsky.UI.Reach.Dropdown AgentSelection;
    string BasePath = string.Empty;

    public void InjectReq()
    {
        string selectedText = AgentSelection.items[AgentSelection.selectedItemIndex].itemName;

        BasePath = Path.Combine(Application.persistentDataPath, @"Agent Presets\" + selectedText + @"\");

        string ReferenceVoicePath = BasePath + "Agent_Voice.wav";
        string ReferenceTextPath = BasePath + "Agent_Transcription.txt";

        // Clear stuff first.
        ttsClientRunner.referenceTexts.Clear();
        ttsClientRunner.referenceAudioFilePaths.Clear();

        // Now continue.
        ttsClientRunner.referenceAudioFilePaths.Add(ReferenceVoicePath);
        ttsClientRunner.referenceTexts.Add(ReferenceTextPath);
    }
}

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;

public class TTSClient
{
    private readonly string _url;
    private readonly string _text;
    private readonly string _apiKey;
    private readonly string _format;
    private readonly int _chunkLength;
    private readonly float _topP;
    private readonly float _temperature;
    private readonly int? _seed;
    private readonly int _maxNewTokens;
    private readonly float _repetitionPenalty;
    private readonly string _outputFilePath;

    private readonly List<string> _referenceTexts;
    private readonly List<AudioClip> _referenceAudios;

    public TTSClient(
        string url,
        string text,
        string apiKey,
        List<string> referenceTexts,
        List<AudioClip> referenceAudios,
        string format = "wav",
        int chunkLength = 0,
        float topP = 0.9f,
        float temperature = 0.9f,
        int? seed = 0,
        int maxNewTokens = 0,
        float repetitionPenalty = 1.1f,
        string outputFilePath = null
    )
    {
        _url = url ?? throw new ArgumentNullException(nameof(url));
        _text = text ?? throw new ArgumentNullException(nameof(text));
        _apiKey = apiKey ?? throw new ArgumentNullException(nameof(apiKey));
        _referenceTexts = referenceTexts ?? throw new ArgumentNullException(nameof(referenceTexts));
        _referenceAudios = referenceAudios ?? throw new ArgumentNullException(nameof(referenceAudios));
        _format = format;
        _chunkLength = chunkLength;
        _topP = topP;
        _temperature = temperature;
        _seed = seed;
        _maxNewTokens = maxNewTokens;
        _repetitionPenalty = repetitionPenalty;

        if (string.IsNullOrEmpty(outputFilePath))
        {
            _outputFilePath = Path.Combine(Application.persistentDataPath, $"output.{_format}");
        }
        else
        {
            _outputFilePath = outputFilePath;
        }
    }

    [Serializable]
    private class ReferenceObject
    {
        public string text;
        public string audio;
        public ReferenceObject(string text, string audio)
        {
            this.text = text;
            this.audio = audio;
        }
    }

    [Serializable]
    private class RequestData
    {
        public string text;
        public ReferenceObject[] references;
        public bool normalize;
        public string format;
        public int max_new_tokens;
        public int chunk_length;
        public float top_p;
        public float repetition_penalty;
        public float temperature;
        public bool streaming;
        public string use_memory_cache;
        public int? seed;
    }

    private ReferenceObject[] CreateReferenceObjects()
    {
        int count = Math.Min(_referenceTexts.Count, _referenceAudios.Count);
        ReferenceObject[] refs = new ReferenceObject[count];

        for (int i = 0; i < count; i++)
        {
            string base64Audio = null;
            if (_referenceAudios[i] != null)
            {
                byte[] wavBytes = AudioClipExtensions.AudioClipToWavBytes(_referenceAudios[i]);
                if (wavBytes != null && wavBytes.Length > 0)
                    base64Audio = Convert.ToBase64String(wavBytes);
            }

            refs[i] = new ReferenceObject(_referenceTexts[i], base64Audio);
        }

        return refs;
    }

    /// <summary>
    /// Coroutine that sends TTS request and saves audio file.
    /// </summary>
    /// <param name="resultCallback">Callback invoked on completion: (bool success, string message)</param>
    public IEnumerator SendRequestAndSaveAudioCoroutine(Action<(bool success, string message)> resultCallback)
    {
        var requestData = new RequestData()
        {
            text = _text,
            references = CreateReferenceObjects(),
            normalize = false,
            format = _format,
            max_new_tokens = _maxNewTokens,
            chunk_length = _chunkLength,
            top_p = _topP,
            repetition_penalty = _repetitionPenalty,
            temperature = _temperature,
            streaming = false,
            use_memory_cache = "on",
            seed = _seed
        };

        string json = JsonUtility.ToJson(requestData);

        byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(json);

        using var webRequest = new UnityWebRequest(_url, UnityWebRequest.kHttpVerbPOST);
        webRequest.uploadHandler = new UploadHandlerRaw(bodyRaw);
        webRequest.downloadHandler = new DownloadHandlerBuffer();
        webRequest.SetRequestHeader("Content-Type", "application/json");
        webRequest.SetRequestHeader("Authorization", "Bearer " + _apiKey);

        yield return webRequest.SendWebRequest();

#if UNITY_2020_1_OR_NEWER
        if (webRequest.result != UnityWebRequest.Result.Success)
#else
        if (webRequest.isNetworkError || webRequest.isHttpError)
#endif
        {
            string errorMsg = !string.IsNullOrEmpty(webRequest.error) ? webRequest.error : "Unknown error";
            resultCallback?.Invoke((false, $"Request error: {errorMsg}"));
            yield break;
        }

        // Save audio bytes to file
        try
        {
            byte[] audioBytes = webRequest.downloadHandler.data;
            if (audioBytes == null || audioBytes.Length == 0)
            {
                resultCallback?.Invoke((false, "Received empty audio data"));
                yield break;
            }

            File.WriteAllBytes(_outputFilePath, audioBytes);
            resultCallback?.Invoke((true, _outputFilePath));
        }
        catch (Exception e)
        {
            resultCallback?.Invoke((false, $"Failed to save audio: {e.Message}"));
        }
    }
}

public static class AudioClipExtensions
{
    public static byte[] AudioClipToWavBytes(AudioClip clip)
    {
        if (clip == null)
            return null;

        var samples = new float[clip.samples * clip.channels];
        clip.GetData(samples, 0);

        byte[] wavBytes = ConvertAudioClipDataToWav(samples, clip.channels, clip.frequency);
        return wavBytes;
    }

    private static byte[] ConvertAudioClipDataToWav(float[] samples, int channels, int sampleRate)
    {
        // Convert float [-1,1] to 16-bit PCM
        short[] intData = new short[samples.Length];
        byte[] bytesData = new byte[samples.Length * 2];

        for (int i = 0; i < samples.Length; i++)
        {
            var sample = Mathf.Clamp(samples[i], -1f, 1f);
            intData[i] = (short)(sample * short.MaxValue);
        }

        Buffer.BlockCopy(intData, 0, bytesData, 0, bytesData.Length);

        // WAV header size
        int headerSize = 44;
        MemoryStream stream = new MemoryStream();

        // RIFF chunk descriptor
        stream.Write(System.Text.Encoding.UTF8.GetBytes("RIFF"), 0, 4);
        stream.Write(BitConverter.GetBytes(headerSize + bytesData.Length - 8), 0, 4);
        stream.Write(System.Text.Encoding.UTF8.GetBytes("WAVE"), 0, 4);

        // fmt subchunk
        stream.Write(System.Text.Encoding.UTF8.GetBytes("fmt "), 0, 4);
        stream.Write(BitConverter.GetBytes(16), 0, 4); // Subchunk1Size (16 for PCM)
        stream.Write(BitConverter.GetBytes((short)1), 0, 2); // AudioFormat (1 is PCM)
        stream.Write(BitConverter.GetBytes((short)channels), 0, 2);
        stream.Write(BitConverter.GetBytes(sampleRate), 0, 4);
        stream.Write(BitConverter.GetBytes(sampleRate * channels * 2), 0, 4); // Byte rate
        stream.Write(BitConverter.GetBytes((short)(channels * 2)), 0, 2); // Block align
        stream.Write(BitConverter.GetBytes((short)16), 0, 2); // Bits per sample

        // data subchunk
        stream.Write(System.Text.Encoding.UTF8.GetBytes("data"), 0, 4);
        stream.Write(BitConverter.GetBytes(bytesData.Length), 0, 4);
        stream.Write(bytesData, 0, bytesData.Length);

        return stream.ToArray();
    }
}

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;

public class TTSClientRunner : MonoBehaviour
{
    [Header("TTS Server Settings")]
    [Tooltip("Your TTS server URL")]
    public string url = "YOUR_URL";

    [Tooltip("API key for authorization")]
    public string apiKey = "YOUR_API_KEY";

    [Header("Text Settings")]
    [TextArea]
    public string text = "Hello, this is a test!";

    [Header("Reference Data (optional)")]
    [Tooltip("Reference texts for voice adaptation")]
    public List<string> referenceTexts = new List<string>() { "Hello" };

    [Tooltip("File paths for reference audio files (relative or absolute)")]
    public List<string> referenceAudioFilePaths = new List<string>();

    [Header("TTS Parameters")]
    [Tooltip("Audio output format (e.g., wav, mp3)")]
    public string format = "wav";

    [Tooltip("Chunk length for streaming (0 disables chunking)")]
    public int chunkLength = 0;

    [Tooltip("Top P parameter")]
    public float topP = 0.9f;

    [Tooltip("Temperature parameter")]
    public float temperature = 0.9f;

    [Tooltip("Random seed (nullable, 0 or null disables)")]
    public int? seed = 0;

    [Tooltip("Maximum new tokens")]
    public int maxNewTokens = 0;

    [Tooltip("Repetition penalty")]
    public float repetitionPenalty = 1.1f;

    [Tooltip("Optional explicit output file path. Leave empty to use persistentDataPath.")]
    public string outputFilePath = "";

    private AudioSource audioSource;

    private void Awake()
    {
        audioSource = GetComponent<AudioSource>();
        if (audioSource == null)
            audioSource = gameObject.AddComponent<AudioSource>();
    }

    public void RunTTSx()
    {
        StartCoroutine(RunTTS());
    }

    private IEnumerator RunTTS()
    {
        Debug.Log("Starting TTS request...");

        // Load reference audio files as AudioClips
        List<AudioClip> referenceAudioClips = new List<AudioClip>();

        for (int i = 0; i < referenceAudioFilePaths.Count; i++)
        {
            string filePath = referenceAudioFilePaths[i];
            if (string.IsNullOrEmpty(filePath))
            {
                referenceAudioClips.Add(null);
                continue;
            }

            string fullPath = filePath;
            if (!Path.IsPathRooted(filePath))
            {
                // Try persistentDataPath first
                fullPath = Path.Combine(Application.persistentDataPath, filePath);

                if (!File.Exists(fullPath))
                {
#if UNITY_ANDROID && !UNITY_EDITOR
                    // Android StreamingAssets access
                    yield return LoadAudioClipFromAndroidStreamingAssets(filePath, clip =>
                    {
                        referenceAudioClips.Add(clip);
                    });
                    continue; // next iteration
#else
                    fullPath = Path.Combine(Application.streamingAssetsPath, filePath);
#endif
                }
            }

            if (File.Exists(fullPath))
            {
                yield return LoadAudioClip(fullPath, clip =>
                {
                    referenceAudioClips.Add(clip);
                });
            }
            else
            {
                Debug.LogWarning($"Reference audio file not found: {fullPath}");
                referenceAudioClips.Add(null);
            }
        }

        // Ensure referenceAudioClips matches referenceTexts count (fill with nulls as needed)
        while (referenceAudioClips.Count < referenceTexts.Count)
        {
            referenceAudioClips.Add(null);
        }

        // Prepare output file path
        string finalOutputFilePath = outputFilePath;
        if (string.IsNullOrEmpty(finalOutputFilePath))
        {
            string outputFolder = Path.Combine(Application.persistentDataPath, "Audio");
            if (!Directory.Exists(outputFolder))
                Directory.CreateDirectory(outputFolder);

            string filename = "tts_output." + format;
            finalOutputFilePath = Path.Combine(outputFolder, filename);
        }

        var ttsClient = new TTSClient(
            url,
            text,
            apiKey,
            referenceTexts,
            referenceAudioClips,
            format,
            chunkLength,
            topP,
            temperature,
            seed,
            maxNewTokens,
            repetitionPenalty,
            finalOutputFilePath);

        yield return ttsClient.SendRequestAndSaveAudioCoroutine(result =>
        {
            if (result.success)
            {
                Debug.Log($"TTS success! Audio saved to: {result.message}");
                StartCoroutine(PlayAudioFromFile(finalOutputFilePath));
            }
            else
            {
                Debug.LogError($"TTS failed: {result.message}");
            }
        });
    }

    private IEnumerator LoadAudioClip(string path, System.Action<AudioClip> callback)
    {
        string url = "file://" + path;
        AudioType audioType = GetAudioTypeFromFormat(format);

        using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(url, audioType))
        {
            yield return www.SendWebRequest();
#if UNITY_2020_1_OR_NEWER
            if (www.result != UnityWebRequest.Result.Success)
#else
            if (www.isNetworkError || www.isHttpError)
#endif
            {
                Debug.LogWarning($"Failed to load reference audio clip '{path}': {www.error}");
                callback?.Invoke(null);
            }
            else
            {
                AudioClip clip = DownloadHandlerAudioClip.GetContent(www);
                callback?.Invoke(clip);
            }
        }
    }

    private IEnumerator PlayAudioFromFile(string path)
    {
        if (!File.Exists(path))
        {
            Debug.LogError($"Playback failed. Audio file does not exist: {path}");
            yield break;
        }

        string url = "file://" + path;
        AudioType audioType = GetAudioTypeFromFormat(format);

        using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(url, audioType))
        {
            yield return www.SendWebRequest();
#if UNITY_2020_1_OR_NEWER
            if (www.result != UnityWebRequest.Result.Success)
#else
            if (www.isNetworkError || www.isHttpError)
#endif
            {
                Debug.LogError($"Failed to load audio clip for playback: {www.error}");
                yield break;
            }
            else
            {
                AudioClip clip = DownloadHandlerAudioClip.GetContent(www);
                if (clip == null)
                {
                    Debug.LogError("Failed to decode audio clip.");
                    yield break;
                }

                audioSource.clip = clip;
                audioSource.Play();
                Debug.Log("Playing TTS audio...");
            }
        }
    }

#if UNITY_ANDROID && !UNITY_EDITOR
    // Helper to load AudioClip from StreamingAssets on Android
    private IEnumerator LoadAudioClipFromAndroidStreamingAssets(string relativePath, System.Action<AudioClip> callback)
    {
        string url = Path.Combine(Application.streamingAssetsPath, relativePath);
        using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.WAV))
        {
            yield return www.SendWebRequest();
#if UNITY_2020_1_OR_NEWER
            if (www.result == UnityWebRequest.Result.Success)
#else
            if (!www.isNetworkError && !www.isHttpError)
#endif
            {
                AudioClip clip = DownloadHandlerAudioClip.GetContent(www);
                callback?.Invoke(clip);
            }
            else
            {
                Debug.LogWarning($"Failed to load {url}: {www.error}");
                callback?.Invoke(null);
            }
        }
    }
#endif

    private AudioType GetAudioTypeFromFormat(string fmt)
    {
        switch (fmt.ToLower())
        {
            case "wav": return AudioType.WAV;
            case "mp3": return AudioType.MPEG;
            case "ogg": return AudioType.OGGVORBIS;
            default: return AudioType.UNKNOWN;
        }
    }
}

please provide all scripts fixed and in full with headers of their names so I can keep track in this chat tysm please I beg u