The other script processes recording and the audio file better than my main script which I need my main script to do the same I just don't need drastic changes to filepaths and stuff just fix how it handles audio based off what you learn from the other script

'other script (learn from this one'
using System.IO;
using TMPro;
using UnityEngine;
#if UNITY_ANDROID
using UnityEngine.Android;
#endif
using UnityEngine.UI;

public class AgentVoiceRecorder : MonoBehaviour
{
    [Header("UI References")]
    public TMP_InputField AgentName; // Reference your agent name UI Text element. Can be TextMeshPro or UI Text as needed.
    public FastAPIAudioTranscriber FAAT;
    private AudioClip recordingClip;
    private bool isRecording = false;
    private int maxRecordingDurationSec = 60;
    private const int sampleRate = 44100;

    /// <summary>
    /// Call this on button Press (pointer down)
    /// </summary>
    public void RecordAgentVoiceStart()
    {
#if UNITY_ANDROID
        if (!Permission.HasUserAuthorizedPermission(Permission.Microphone))
        {
            Debug.Log("Requesting Microphone permission...");
            Permission.RequestUserPermission(Permission.Microphone);
            return;
        }
#endif

        if (isRecording)
            return;

        if (Microphone.devices.Length == 0)
        {
            Debug.LogWarning("No microphone detected!");
            return;
        }

        isRecording = true;
        recordingClip = Microphone.Start(null, false, maxRecordingDurationSec, sampleRate);
        Debug.Log("Recording started...");
    }

    /// <summary>
    /// Call this on button Release (pointer up)
    /// </summary>
    public void RecordAgentVoiceStop()
    {
        if (!isRecording)
            return;

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

        if (length <= 0)
        {
            Debug.LogWarning("Recording failed or too short.");
            return;
        }

        Debug.Log($"Recording stopped. Length: {length} samples");

        // Trim recording to actual recorded length
        float[] samples = new float[recordingClip.samples * recordingClip.channels];
        recordingClip.GetData(samples, 0);

        float[] trimmedSamples = new float[length * recordingClip.channels];
        System.Array.Copy(samples, trimmedSamples, trimmedSamples.Length);

        AudioClip trimmedClip = AudioClip.Create("trimmed", length, recordingClip.channels, sampleRate, false);
        trimmedClip.SetData(trimmedSamples, 0);

        // Build folder path for saving
        string baseFolder = Path.Combine(Application.persistentDataPath, "Agent Presets");
        string agentFolderName = SanitizeFileName(AgentName.text);
        string agentFolderPath = Path.Combine(baseFolder, agentFolderName);

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

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

        bool success = SaveWavFile(filePath, trimmedClip);

        FAAT.audioFilePath = filePath;

        if (success)
            Debug.Log($"Recording saved successfully to {filePath}");
        else
            Debug.LogError("Failed to save recording.");
    }

    #region WAV FILE SAVING CODE

    private bool SaveWavFile(string filepath, AudioClip clip)
    {
        try
        {
            using (var fileStream = CreateEmptyWav(filepath, clip))
            {
                ConvertAndWrite(fileStream, clip);
                WriteHeader(fileStream, clip);
            }
            return true;
        }
        catch (System.Exception e)
        {
            Debug.LogError("Error saving wav file: " + e);
            return false;
        }
    }

    private FileStream CreateEmptyWav(string filepath, AudioClip clip)
    {
        var fileStream = new FileStream(filepath, FileMode.Create);
        byte emptyByte = new byte();

        // RIFF header
        fileStream.Write(System.Text.Encoding.ASCII.GetBytes("RIFF"), 0, 4);
        fileStream.Write(System.BitConverter.GetBytes(0), 0, 4); // Placeholder for file size
        fileStream.Write(System.Text.Encoding.ASCII.GetBytes("WAVE"), 0, 4);

        // fmt chunk
        fileStream.Write(System.Text.Encoding.ASCII.GetBytes("fmt "), 0, 4);
        fileStream.Write(System.BitConverter.GetBytes(16), 0, 4); // Subchunk1Size for PCM
        fileStream.Write(System.BitConverter.GetBytes((short)1), 0, 2); // Audio format (1=PCM)
        fileStream.Write(System.BitConverter.GetBytes((short)clip.channels), 0, 2);
        fileStream.Write(System.BitConverter.GetBytes(clip.frequency), 0, 4);
        fileStream.Write(System.BitConverter.GetBytes(clip.frequency * clip.channels * 2), 0, 4); // ByteRate
        fileStream.Write(System.BitConverter.GetBytes((short)(clip.channels * 2)), 0, 2); // BlockAlign
        fileStream.Write(System.BitConverter.GetBytes((short)16), 0, 2); // BitsPerSample

        // data chunk
        fileStream.Write(System.Text.Encoding.ASCII.GetBytes("data"), 0, 4);
        fileStream.Write(System.BitConverter.GetBytes(0), 0, 4); // Placeholder for data chunk size

        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];
        const float rescaleFactor = 32767; // to convert float to Int16

        for (int i = 0; i < samples.Length; i++)
            intData[i] = (short)(samples[i] * rescaleFactor);

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

        for (int i = 0; i < intData.Length; i++)
        {
            byte[] byteArr = System.BitConverter.GetBytes(intData[i]);
            byteArr.CopyTo(bytesData, i * 2);
        }

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

    private void WriteHeader(FileStream fileStream, AudioClip clip)
    {
        int fileSize = (int)fileStream.Length;

        // ChunkSize (file size - 8) at offset 4
        fileStream.Seek(4, SeekOrigin.Begin);
        fileStream.Write(System.BitConverter.GetBytes(fileSize - 8), 0, 4);

        // Subchunk2Size (data length) at offset 40
        fileStream.Seek(40, SeekOrigin.Begin);
        fileStream.Write(System.BitConverter.GetBytes(fileSize - 44), 0, 4);
    }

    #endregion

    private string SanitizeFileName(string filename)
    {
        if (string.IsNullOrEmpty(filename))
            return "UnknownAgent";

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

        return filename;
    }
}

'main script'
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)
    {
        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;
        }

        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;
        }

        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);
        // Placeholder 44 byte WAV header
        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);
    }
}