Got it! I’ll add a Play button to your existing code, which will play the current (possibly edited) audio buffer, starting from the beginning or selection start if a selection exists.
What I’ll add:
- A Play button next to Save.
- Playback support using NAudio's
WaveOutEvent and BufferedWaveProvider.
- The ability to play the current (edited) audio buffer, including reflecting edits.
- Stop playback when the form closes or when a new file is loaded.
Here is the full updated code with a Play button and playback:
using System;
using System.Drawing;
using System.Windows.Forms;
using NAudio.Wave;
namespace SimpleAudioEditor
{
// DoubleBufferedPanel to reduce flickering
public class DoubleBufferedPanel : Panel
{
public DoubleBufferedPanel()
{
this.DoubleBuffered = true;
this.SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.UserPaint |
ControlStyles.OptimizedDoubleBuffer, true);
this.UpdateStyles();
}
}
public partial class AudioEditorForm : Form
{
private float[] audioSamples; // normalized samples (-1 to 1)
private WaveFormat waveFormat;
private string currentFilePath;
private bool isSelecting = false;
private int selectionStart = -1;
private int selectionEnd = -1;
private int sampleRate;
private Button btnLoad;
private Button btnDelete;
private Button btnSave;
private Button btnPlay;
private DoubleBufferedPanel waveformPanel;
// Playback fields
private IWavePlayer waveOut;
private BufferedWaveProvider bufferedWaveProvider;
public AudioEditorForm()
{
InitializeComponent();
// Form properties
this.Text = "Simple Audio Editor";
this.Width = 800;
this.Height = 400;
// Load Button
btnLoad = new Button()
{
Text = "Load WAV",
Left = 10,
Top = 10,
Width = 100
};
btnLoad.Click += BtnLoad_Click;
this.Controls.Add(btnLoad);
// Delete Button
btnDelete = new Button()
{
Text = "Delete Selection",
Left = 120,
Top = 10,
Width = 120,
Enabled = false
};
btnDelete.Click += BtnDelete_Click;
this.Controls.Add(btnDelete);
// Save Button
btnSave = new Button()
{
Text = "Save",
Left = 250,
Top = 10,
Width = 100,
Enabled = false
};
btnSave.Click += BtnSave_Click;
this.Controls.Add(btnSave);
// Play Button
btnPlay = new Button()
{
Text = "Play",
Left = 360,
Top = 10,
Width = 100,
Enabled = false
};
btnPlay.Click += BtnPlay_Click;
this.Controls.Add(btnPlay);
// Replace Panel with DoubleBufferedPanel to fix flickering
waveformPanel = new DoubleBufferedPanel()
{
Left = 10,
Top = 50,
Width = this.ClientSize.Width - 20,
Height = this.ClientSize.Height - 60,
BorderStyle = BorderStyle.FixedSingle,
BackColor = Color.Black,
Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right
};
waveformPanel.Paint += WaveformPanel_Paint;
waveformPanel.MouseDown += WaveformPanel_MouseDown;
waveformPanel.MouseMove += WaveformPanel_MouseMove;
waveformPanel.MouseUp += WaveformPanel_MouseUp;
this.Controls.Add(waveformPanel);
this.FormClosing += AudioEditorForm_FormClosing;
}
private void BtnLoad_Click(object sender, EventArgs e)
{
using (var ofd = new OpenFileDialog())
{
ofd.Filter = "WAV files (*.wav)|*.wav";
if (ofd.ShowDialog() == DialogResult.OK)
{
currentFilePath = ofd.FileName;
LoadWaveFile(currentFilePath);
btnPlay.Enabled = audioSamples != null && audioSamples.Length > 0;
}
}
}
private void LoadWaveFile(string path)
{
StopPlayback();
try
{
using (var reader = new AudioFileReader(path))
{
waveFormat = reader.WaveFormat;
sampleRate = waveFormat.SampleRate;
var wholeFile = new float[reader.Length / 4];
int offset = 0;
int samplesRead;
var buffer = new float[1024];
while ((samplesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
{
Array.Copy(buffer, 0, wholeFile, offset, samplesRead);
offset += samplesRead;
}
audioSamples = wholeFile;
}
selectionStart = -1;
selectionEnd = -1;
btnDelete.Enabled = false;
btnSave.Enabled = true;
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))
{
int samplesPerPixel = Math.Max(1, audioSamples.Length / w);
for (int x = 0; x < w; x++)
{
int startSample = x * samplesPerPixel;
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 = audioSamples.Length;
int x1 = (int)((double)selectionStart / wSamples * w);
int x2 = (int)((double)selectionEnd / 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.Blue)))
{
e.Graphics.FillRectangle(selectionBrush, rectX, 0, rectW, h);
}
using (var pen = new Pen(Color.Blue, 2))
{
e.Graphics.DrawRectangle(pen, rectX, 0, rectW, h - 1);
}
}
}
}
private void WaveformPanel_MouseDown(object sender, MouseEventArgs e)
{
if (audioSamples == null) return;
isSelecting = true;
int w = waveformPanel.ClientSize.Width;
int sampleIndex = (int)((double)e.X / w * audioSamples.Length);
sampleIndex = Math.Max(0, Math.Min(sampleIndex, 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 = (int)((double)e.X / w * audioSamples.Length);
sampleIndex = Math.Max(0, Math.Min(sampleIndex, audioSamples.Length - 1));
selectionEnd = sampleIndex;
waveformPanel.Invalidate();
btnDelete.Enabled = Math.Abs(selectionEnd - selectionStart) > 0;
}
private void WaveformPanel_MouseUp(object sender, MouseEventArgs e)
{
if (audioSamples == null) return;
isSelecting = false;
if (Math.Abs(selectionEnd - selectionStart) == 0)
{
selectionStart = -1;
selectionEnd = -1;
btnDelete.Enabled = false;
}
else
{
btnDelete.Enabled = true;
}
waveformPanel.Invalidate();
}
private void BtnDelete_Click(object sender, EventArgs e)
{
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 newLength = audioSamples.Length - (end - start);
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;
btnDelete.Enabled = false;
waveformPanel.Invalidate();
}
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 BtnPlay_Click(object sender, EventArgs e)
{
if (audioSamples == null || audioSamples.Length == 0) return;
StopPlayback();
waveOut = new WaveOutEvent();
// Create BufferedWaveProvider with the waveFormat of audioSamples
bufferedWaveProvider = new BufferedWaveProvider(waveFormat)
{
BufferDuration = TimeSpan.FromSeconds(30), // a reasonable buffer size
DiscardOnBufferOverflow = true
};
// Convert float samples to byte buffer according to waveFormat.BitsPerSample & Channels
byte[] audioBuffer;
if (waveFormat.Encoding == WaveFormatEncoding.IeeeFloat)
{
audioBuffer = new byte[audioSamples.Length * 4];
Buffer.BlockCopy(audioSamples, 0, audioBuffer, 0, audioBuffer.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);
}
audioBuffer = new byte[int16Samples.Length * 2];
Buffer.BlockCopy(int16Samples, 0, audioBuffer, 0, audioBuffer.Length);
}
else
{
MessageBox.Show("Unsupported bit depth for playback: " + waveFormat.BitsPerSample);
return;
}
int startSample = 0;
int endSample = audioSamples.Length;
if (selectionStart >= 0 && selectionEnd >= 0 && selectionEnd != selectionStart)
{
startSample = Math.Min(selectionStart, selectionEnd);
endSample = Math.Max(selectionStart, selectionEnd);
}
int bytesPerSample = waveFormat.BitsPerSample / 8;
int channels = waveFormat.Channels;
// Calculate the segment range in bytes
int startPosBytes = startSample * bytesPerSample;
int lengthBytes = (endSample - startSample) * bytesPerSample;
// For stereo data, audioSamples array length = samples * channels
// So, if channels > 1, we need to multiply accordingly:
startPosBytes = startSample * bytesPerSample * channels;
lengthBytes = (endSample - startSample) * bytesPerSample * channels;
// Make sure indexes are within bounds
startPosBytes = Math.Max(0, Math.Min(startPosBytes, audioBuffer.Length));
lengthBytes = Math.Max(0, Math.Min(lengthBytes, audioBuffer.Length - startPosBytes));
bufferedWaveProvider.ClearBuffer();
bufferedWaveProvider.AddSamples(audioBuffer, startPosBytes, lengthBytes);
waveOut.Init(bufferedWaveProvider);
waveOut.Play();
btnPlay.Enabled = false;
waveOut.PlaybackStopped += (s, args) =>
{
// Re-enable Play button after playback
if (this.InvokeRequired)
{
this.Invoke((Action)(() => btnPlay.Enabled = true));
}
else
{
btnPlay.Enabled = true;
}
StopPlayback();
};
}
private void StopPlayback()
{
if (waveOut != null)
{
waveOut.Stop();
waveOut.Dispose();
waveOut = null;
}
if (bufferedWaveProvider != null)
{
bufferedWaveProvider.ClearBuffer();
bufferedWaveProvider = null;
}
btnPlay.Enabled = (audioSamples != null && audioSamples.Length > 0);
}
private void AudioEditorForm_FormClosing(object sender, FormClosingEventArgs e)
{
StopPlayback();
}
}
}
Summary of playback additions:
- Added
btnPlay and wired up its click event.
- Created a NAudio
WaveOutEvent and BufferedWaveProvider on play.
- Converts your current
audioSamples floats back to PCM bytes for playback.
- Plays full audio or only selection if one is made.
- Disables Play button while audio is playing; re-enables after playback.
- Stops playback safely when loading new files or closing the form.
To test:
- Run your app.
- Load a WAV file.
- Select a region or leave none selected.
- Click Play (audio plays your edited buffer or selected segment).
- Click Delete to cut a segment.
- Save changes with Save.
Let me know if you want pause/stop buttons or waveform position tracking next!