Unable to get wave form image for smaller duration audio stream using this code. I am getting totally blank image. Is there any way to get correct wave form image for smaller duration audio stream. I am using NAudio's AudioFileReader function here.
Bitmap bim = new Bitmap(1800,200);
System.Drawing.Graphics g = Graphics.FromImage(bim);
using (var reader = new AudioFileReader("D:\\Test-Songs\\DawnJay.mp3"))
{
var samples = reader.Length / (reader.WaveFormat.Channels * reader.WaveFormat.BitsPerSample / 8);
var f = 0.0f;
var max = 0.0f;
// waveform will be a maximum of 4000 pixels wide:
var batch = (int)Math.Max(40, samples / 4000);
var mid = 100;
var yScale = 100;
float[] buffer = new float[batch];
int read;
var xPos = 0;
Pen pen = new Pen(Color.Red, 2.0f);
g.Clear(Color.Black);
while ((read = reader.Read(buffer, 0, batch)) == batch)
{
for (int n = 0; n < read; n++)
{
max = Math.Max(Math.Abs(buffer[n]), max);
}
int X1 = xPos;
int X2 = xPos;
float Y1 = mid + (max * yScale);
float Y2 = mid - (max * yScale);
g.DrawLine(pen,X1, Y1, X2, Y2);
max = 0;
xPos++;
}
}
bim.Save("D:\\Images\\waveform.png");
Your code here:
var batch = (int)Math.Max(40, samples / 4000);
This says that you are going to accept a minimum of 40 samples per column. For a small file this might mean that your data gets reduced to only a small number of columns of data in the output bitmap. If you are then scaling that data down to fit into a display area on screen, your audio data might disappear.
Try changing your minimum number of samples per block to a smaller value, which should give you a chance at actually visualizing small audio files. You should probably do full Min-Max calculations, or else your plots for very small files will look totally wrong.