Below is my Visual Studio C# code for Visualizing Audio, Editing Audio, Playing Audio. I like how it is but there's some annoying bugs like if I press space bar it plays normally and the seek bar is visible and working correctly and when I press space again it stops the playback as intended, however whenever I press space again the seek bar becomes invisible playback works fine until I try to stop it with another space bar press, after that it just starts over and keeps playing with no way to stop anymore. Please fix and return entire script fixed.

using System;
using System.Drawing;
using System.Windows.Forms;
using NAudio.Wave;
using Timer = System.Windows.Forms.Timer;

namespace ByteBreath
{
    public partial class AudioEditorForm : Form
    {
        private float[] audioSamples;
        private WaveFormat waveFormat;
        private string currentFilePath;
        public string SelectionPath;
        public DataSetMaker dataSetMaker;
        private bool isSelecting = false;
        private int selectionStart = -1;
        private int selectionEnd = -1;

        private int sampleRate;

        private WaveOutEvent waveOut;
        private BufferedWaveProvider bufferedWaveProvider;

        private Timer playbackTimer;
        private long playStartSample = 0;
        private long playEndSample = 0;
        private bool isPlaying = false;

        private int viewStartSample = 0;
        private int viewSamples = 0;
        private const int minViewSamples = 1000;
        private const int maxViewSamplesFactor = 1;

        private bool isMouseInWaveform = false;

        public AudioEditorForm(DataSetMaker dataSetMaker)
        {
            InitializeComponent();

            this.dataSetMaker = dataSetMaker ?? new DataSetMaker();

            waveformPanel.Paint += WaveformPanel_Paint;
            waveformPanel.MouseDown += WaveformPanel_MouseDown;
            waveformPanel.MouseMove += WaveformPanel_MouseMove;
            waveformPanel.MouseUp += WaveformPanel_MouseUp;
            waveformPanel.MouseWheel += WaveformPanel_MouseWheel;
            waveformPanel.MouseEnter += WaveformPanel_MouseEnter;
            waveformPanel.MouseLeave += WaveformPanel_MouseLeave;
            waveformPanel.KeyDown += WaveformPanel_KeyDown;

            playbackTimer = new Timer();
            playbackTimer.Interval = 30;
            playbackTimer.Tick += PlaybackTimer_Tick;

            this.KeyPreview = true;
            this.KeyDown += AudioEditorForm_KeyDown;

            btnSave.Enabled = false;
        }

        private void WaveformPanel_MouseEnter(object sender, EventArgs e)
        {
            isMouseInWaveform = true;
            waveformPanel.Focus();
        }

        private void WaveformPanel_MouseLeave(object sender, EventArgs e)
        {
            isMouseInWaveform = false;
        }

        private void WaveformPanel_MouseWheel(object sender, MouseEventArgs e)
        {
            if (isMouseInWaveform)
                ZoomWaveform(e);
        }

        private void ZoomWaveform(MouseEventArgs e)
        {
            if (audioSamples == null || audioSamples.Length == 0)
                return;

            int panelWidth = waveformPanel.ClientSize.Width;
            if (panelWidth <= 0)
                return;

            if (viewSamples == 0)
            {
                viewSamples = audioSamples.Length;
                viewStartSample = 0;
            }

            float zoomFactor = 1.0f - (e.Delta / 1200.0f);
            if (zoomFactor <= 0) zoomFactor = 0.1f;

            int newViewSamples = (int)(viewSamples * zoomFactor);

            int minSamples = minViewSamples;
            int maxSamples = audioSamples.Length * maxViewSamplesFactor;
            if (maxSamples < minSamples) maxSamples = minSamples;

            if (newViewSamples < minSamples) newViewSamples = minSamples;
            if (newViewSamples > maxSamples) newViewSamples = maxSamples;

            if (newViewSamples == viewSamples)
                return;

            double mouseRatio = (double)e.X / panelWidth;
            mouseRatio = Math.Clamp(mouseRatio, 0.0, 1.0);

            long mouseSample = viewStartSample + (long)(mouseRatio * viewSamples);
            long newViewStartSample = mouseSample - (long)(mouseRatio * newViewSamples);

            if (newViewStartSample < 0) newViewStartSample = 0;
            if (newViewStartSample + newViewSamples > audioSamples.Length)
                newViewStartSample = audioSamples.Length - newViewSamples;
            if (newViewStartSample < 0)
                newViewStartSample = 0;

            viewStartSample = (int)newViewStartSample;
            viewSamples = newViewSamples;

            waveformPanel.Invalidate();
        }

        private void LoadWaveFile(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
                return;

            try
            {
                currentFilePath = path;

                waveOut?.Stop();
                waveOut?.Dispose();
                waveOut = null;
                bufferedWaveProvider = null;

                audioSamples = null;
                selectionStart = -1;
                selectionEnd = -1;

                using (var reader = new AudioFileReader(path))
                {
                    waveFormat = reader.WaveFormat;
                    sampleRate = waveFormat.SampleRate;

                    long totalFloatSamplesLong = reader.Length / 4;

                    if (totalFloatSamplesLong > int.MaxValue)
                        throw new InvalidOperationException("Audio file too large.");

                    int sampleCount = (int)totalFloatSamplesLong;
                    audioSamples = new float[sampleCount];

                    int offset = 0;
                    int samplesRead;
                    var buffer = new float[1024];

                    reader.Position = 0;
                    while ((samplesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        int copyCount = Math.Min(samplesRead, sampleCount - offset);
                        Array.Copy(buffer, 0, audioSamples, offset, copyCount);
                        offset += copyCount;
                    }
                }

                viewStartSample = 0;
                viewSamples = audioSamples.Length;

                btnSave.Enabled = true;

                playStartSample = 0;
                playEndSample = audioSamples.Length - 1;

                waveOut = new WaveOutEvent();
                waveOut.PlaybackStopped += WaveOut_PlaybackStopped;

                bufferedWaveProvider = new BufferedWaveProvider(waveFormat)
                {
                    BufferLength = audioSamples.Length * waveFormat.BlockAlign
                };
                bufferedWaveProvider.ClearBuffer();

                byte[] byteBuffer = new byte[audioSamples.Length * 4];
                Buffer.BlockCopy(audioSamples, 0, byteBuffer, 0, byteBuffer.Length);
                bufferedWaveProvider.AddSamples(byteBuffer, 0, byteBuffer.Length);

                waveOut.Init(bufferedWaveProvider);

                waveformPanel.Invalidate();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to load WAV: " + ex.Message);
            }
        }

        private void WaveformPanel_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(Color.Black);
            if (audioSamples == null || audioSamples.Length == 0)
            {
                using (var brush = new SolidBrush(Color.White))
                    e.Graphics.DrawString("No audio loaded", this.Font, brush, new PointF(10, 10));
                return;
            }

            int w = waveformPanel.ClientSize.Width;
            int h = waveformPanel.ClientSize.Height;

            using (var pen = new Pen(Color.White))
            {
                if (viewSamples == 0)
                    viewSamples = audioSamples.Length;
                if (viewStartSample + viewSamples > audioSamples.Length)
                    viewStartSample = audioSamples.Length - viewSamples;

                if (viewStartSample < 0) viewStartSample = 0;
                if (viewSamples <= 0) viewSamples = audioSamples.Length;

                int samplesPerPixel = Math.Max(1, viewSamples / w);

                for (int x = 0; x < w; x++)
                {
                    int startSample = viewStartSample + x * samplesPerPixel;
                    if (startSample >= audioSamples.Length)
                        break;
                    int endSample = Math.Min(audioSamples.Length, startSample + samplesPerPixel);

                    float min = 1f;
                    float max = -1f;
                    for (int s = startSample; s < endSample; s++)
                    {
                        float val = audioSamples[s];
                        if (val < min) min = val;
                        if (val > max) max = val;
                    }

                    int yMax = (int)((1 - (max + 1) / 2) * h);
                    int yMin = (int)((1 - (min + 1) / 2) * h);

                    e.Graphics.DrawLine(pen, x, yMin, x, yMax);
                }
            }

            if (selectionStart >= 0 && selectionEnd >= 0 && selectionEnd != selectionStart)
            {
                int wSamples = viewSamples;
                int visibleStart = viewStartSample;
                int x1 = (int)((double)(selectionStart - visibleStart) / wSamples * w);
                int x2 = (int)((double)(selectionEnd - visibleStart) / wSamples * w);

                int rectX = Math.Min(x1, x2);
                int rectW = Math.Abs(x2 - x1);

                if (rectW > 0)
                {
                    using (var selectionBrush = new SolidBrush(Color.FromArgb(100, Color.Green)))
                        e.Graphics.FillRectangle(selectionBrush, rectX, 0, rectW, h);

                    using (var pen = new Pen(Color.Red, 2))
                        e.Graphics.DrawRectangle(pen, rectX, 0, rectW, h - 1);
                }
            }

            if (isPlaying && audioSamples != null && waveOut != null)
            {
                long bytesPerSample = waveFormat.BitsPerSample / 8 * waveFormat.Channels;
                long currentSample = 0;

                try
                {
                    currentSample = waveOut.GetPosition() / bytesPerSample + playStartSample;
                }
                catch
                {
                    currentSample = 0;
                }

                if (currentSample > audioSamples.Length)
                    currentSample = audioSamples.Length;

                long segmentLength = playEndSample - playStartSample + 1;
                if (segmentLength <= 0) segmentLength = audioSamples.Length;

                if (currentSample > playEndSample)
                    currentSample = playEndSample;

                int x = 0;

                if (selectionStart >= 0 && selectionEnd >= 0 && selectionStart != selectionEnd)
                {
                    int wSamples = viewSamples;
                    int visibleStart = viewStartSample;

                    int sx1 = (int)((double)(selectionStart - visibleStart) / wSamples * w);
                    int sx2 = (int)((double)(selectionEnd - visibleStart) / wSamples * w);

                    int rectX = Math.Min(sx1, sx2);
                    int rectW = Math.Abs(sx2 - sx1);

                    if (segmentLength > 0)
                        x = rectX + (int)((double)(currentSample - playStartSample) / segmentLength * rectW);
                    else
                        x = rectX;
                }
                else
                {
                    int wSamples = viewSamples;
                    int visibleStart = viewStartSample;
                    x = (int)((double)(currentSample - visibleStart) / wSamples * w);
                }

                if (x >= 0 && x < w)
                {
                    using (var pen = new Pen(Color.Red, 2))
                        e.Graphics.DrawLine(pen, x, 0, x, h);
                }
            }
        }

        private void WaveformPanel_MouseDown(object sender, MouseEventArgs e)
        {
            if (audioSamples == null) return;

            isSelecting = true;
            int w = waveformPanel.ClientSize.Width;

            int sampleIndex = viewStartSample + (int)((double)e.X / w * viewSamples);
            sampleIndex = Math.Clamp(sampleIndex, 0, audioSamples.Length - 1);

            selectionStart = sampleIndex;
            selectionEnd = sampleIndex;
            waveformPanel.Invalidate();
        }

        private void WaveformPanel_MouseMove(object sender, MouseEventArgs e)
        {
            if (audioSamples == null || !isSelecting) return;

            int w = waveformPanel.ClientSize.Width;
            int sampleIndex = viewStartSample + (int)((double)e.X / w * viewSamples);
            sampleIndex = Math.Clamp(sampleIndex, 0, audioSamples.Length - 1);

            selectionEnd = sampleIndex;
            waveformPanel.Invalidate();
        }

        private void WaveformPanel_MouseUp(object sender, MouseEventArgs e)
        {
            if (audioSamples == null) return;

            isSelecting = false;

            if (Math.Abs(selectionEnd - selectionStart) == 0)
            {
                selectionStart = -1;
                selectionEnd = -1;
            }
            waveformPanel.Invalidate();
        }

        private void DeleteSelection()
        {
            if (audioSamples == null) return;
            if (selectionStart < 0 || selectionEnd < 0) return;

            int start = Math.Min(selectionStart, selectionEnd);
            int end = Math.Max(selectionStart, selectionEnd);
            if (end == start) return;

            int deletedCount = end - start;

            int oldViewStartSample = viewStartSample;
            int oldViewSamples = viewSamples;

            int newLength = audioSamples.Length - deletedCount;
            float[] newSamples = new float[newLength];

            Array.Copy(audioSamples, 0, newSamples, 0, start);
            Array.Copy(audioSamples, end, newSamples, start, audioSamples.Length - end);

            audioSamples = newSamples;

            selectionStart = -1;
            selectionEnd = -1;

            waveOut?.Stop();

            bufferedWaveProvider = new BufferedWaveProvider(waveFormat)
            {
                BufferLength = audioSamples.Length * waveFormat.BlockAlign
            };
            bufferedWaveProvider.ClearBuffer();

            byte[] byteBuffer = new byte[audioSamples.Length * 4];
            Buffer.BlockCopy(audioSamples, 0, byteBuffer, 0, byteBuffer.Length);
            bufferedWaveProvider.AddSamples(byteBuffer, 0, byteBuffer.Length);

            waveOut?.Init(bufferedWaveProvider);

            playStartSample = 0;
            playEndSample = audioSamples.Length - 1;

            if (oldViewStartSample >= end)
            {
                viewStartSample = Math.Max(0, oldViewStartSample - deletedCount);
                viewSamples = oldViewSamples;
            }
            else if (oldViewStartSample < end && (oldViewStartSample + oldViewSamples) > start)
            {
                int newViewSamples = oldViewSamples - deletedCount;
                if (newViewSamples < minViewSamples) newViewSamples = Math.Min(minViewSamples, audioSamples.Length);
                if (newViewSamples > audioSamples.Length) newViewSamples = audioSamples.Length;

                viewStartSample = oldViewStartSample;
                if (viewStartSample > audioSamples.Length - newViewSamples)
                    viewStartSample = audioSamples.Length - newViewSamples;
                if (viewStartSample < 0) viewStartSample = 0;

                viewSamples = newViewSamples;
            }
            else
            {
                viewStartSample = oldViewStartSample;
                viewSamples = oldViewSamples;
            }

            if (viewSamples > audioSamples.Length)
            {
                viewSamples = audioSamples.Length;
                viewStartSample = 0;
            }

            waveformPanel.Invalidate();
            isPlaying = false;
        }

        private void WaveformPanel_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (selectionStart >= 0 && selectionEnd >= 0 && selectionEnd != selectionStart)
                {
                    DeleteSelection();
                    e.Handled = true;
                }
            }
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            if (audioSamples == null || string.IsNullOrEmpty(currentFilePath)) return;

            try
            {
                using (var writer = new WaveFileWriter(currentFilePath, waveFormat))
                {
                    if (waveFormat.Encoding == WaveFormatEncoding.IeeeFloat)
                    {
                        writer.WriteSamples(audioSamples, 0, audioSamples.Length);
                    }
                    else if (waveFormat.BitsPerSample == 16)
                    {
                        short[] int16Samples = new short[audioSamples.Length];
                        for (int i = 0; i < audioSamples.Length; i++)
                        {
                            float sample = audioSamples[i];
                            sample = Math.Max(-1f, Math.Min(1f, sample));
                            int16Samples[i] = (short)(sample * short.MaxValue);
                        }
                        byte[] bytes = new byte[int16Samples.Length * 2];
                        Buffer.BlockCopy(int16Samples, 0, bytes, 0, bytes.Length);
                        writer.Write(bytes, 0, bytes.Length);
                    }
                    else
                    {
                        MessageBox.Show("Unsupported bit depth: " + waveFormat.BitsPerSample);
                        return;
                    }
                }
                MessageBox.Show("File saved to " + currentFilePath);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to save WAV: " + ex.Message);
            }
        }

        private void TogglePlayPause()
        {
            if (audioSamples == null || waveOut == null || waveFormat == null) return;

            if (!isPlaying)
            {
                if (selectionStart >= 0 && selectionEnd >= 0 && selectionEnd != selectionStart)
                {
                    playStartSample = Math.Min(selectionStart, selectionEnd);
                    playEndSample = Math.Max(selectionStart, selectionEnd);
                }
                else
                {
                    playStartSample = 0;
                    playEndSample = audioSamples.Length - 1;
                }

                waveOut.Stop();

                long bytesPerSample = 4;

                long totalSamples = playEndSample - playStartSample + 1;

                if (playStartSample < 0 || playEndSample >= audioSamples.Length || totalSamples <= 0)
                {
                    MessageBox.Show("Invalid selection for playback.");
                    return;
                }

                try
                {
                    long lengthBytes = totalSamples * bytesPerSample;

                    if (lengthBytes > int.MaxValue)
                    {
                        MessageBox.Show("Selection too large for playback.");
                        return;
                    }

                    int intLengthBytes = (int)lengthBytes;

                    if (bufferedWaveProvider != null)
                    {
                        bufferedWaveProvider.ClearBuffer();
                    }

                    bufferedWaveProvider = new BufferedWaveProvider(waveFormat)
                    {
                        BufferLength = intLengthBytes
                    };

                    byte[] byteBuffer = new byte[intLengthBytes];
                    int byteOffset = (int)(playStartSample * bytesPerSample);

                    if (byteOffset < 0 || (byteOffset + intLengthBytes) > audioSamples.Length * 4)
                    {
                        MessageBox.Show("Playback selection range is out of audio sample bounds.");
                        return;
                    }

                    Buffer.BlockCopy(audioSamples, byteOffset, byteBuffer, 0, intLengthBytes);
                    bufferedWaveProvider.AddSamples(byteBuffer, 0, intLengthBytes);

                    waveOut.Init(bufferedWaveProvider);

                    waveOut.Play();
                    isPlaying = true;
                    playbackTimer.Start();
                }
                catch
                {
                    MessageBox.Show("Error occurred during playback start.");
                    return;
                }
            }
            else
            {
                waveOut.Pause();
                isPlaying = false;
                playbackTimer.Stop();
            }

            waveformPanel.Invalidate();
        }

        private void PlaybackTimer_Tick(object sender, EventArgs e)
        {
            if (!isPlaying) return;

            long bytesPerSample = waveFormat.BitsPerSample / 8 * waveFormat.Channels;
            long currentSample = 0;

            try
            {
                if (bufferedWaveProvider != null && waveOut != null)
                {
                    currentSample = waveOut.GetPosition() / bytesPerSample + playStartSample;
                }
            }
            catch
            {
                currentSample = 0;
            }

            if (currentSample > playEndSample)
            {
                waveOut.Stop();
                return;
            }

            waveformPanel.Invalidate();
        }

        private void WaveOut_PlaybackStopped(object sender, StoppedEventArgs e)
        {
            isPlaying = false;
            playbackTimer.Stop();
            waveformPanel.Invalidate();
        }

        private void AudioEditorForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
            {
                if (!e.Handled)
                {
                    TogglePlayPause();
                    e.Handled = true;
                }
            }
        }

        private void AudioEditorForm_Load(object sender, EventArgs e)
        {
            if (dataSetMaker == null)
                dataSetMaker = new DataSetMaker();

            if (!string.IsNullOrEmpty(SelectionPath))
            {
                LoadWaveFile(SelectionPath);
            }
            else
            {
                btnSave.Enabled = false;
            }
        }
    }
}