0

当我试图通过将 mp3 流传递给以下函数来生成波形图像时,它会在 g.DrawLine 调用中引发溢出异常。请纠正我哪里出错了。非常感谢任何帮助。

public static void DrawNormalizedAudio(ref float[] data, Color color)
{
   Bitmap bmp= new Bitmap(1800,200);            

   int BORDER_WIDTH = 5;
   int width = bmp.Width - (2 * BORDER_WIDTH);
   int height = bmp.Height - (2 * BORDER_WIDTH);

   using (Graphics g = Graphics.FromImage(bmp))
   {
      g.Clear(Color.Black);
      Pen pen = new Pen(color);
      int size = data.Length;
      for (int iPixel = 0; iPixel < width; iPixel++)
      {
        // determine start and end points within WAV
           int start = (int)((float)iPixel * ((float)size / (float)width));
           int end = (int)((float)(iPixel + 1) * ((float)size / (float)width));
           float min = float.MaxValue;
           float max = float.MinValue;
           for (int i = start; i < end; i++)
           {
              float val = data[i];
              min = val < min ? val : min;
              max = val > max ? val : max;
           }
           int yMax = BORDER_WIDTH + height - (int)((max + 1) * .5 * height);
           int yMin = BORDER_WIDTH + height - (int)((min + 1) * .5 * height);
           g.DrawLine(pen, iPixel + BORDER_WIDTH, yMax,
           iPixel + BORDER_WIDTH, yMin);
          }
        }

        bmp.Save("D:\\waveimage.png"); 
    }

    public float[] FloatArrayFromStream(System.IO.MemoryStream stream)
    {
        return FloatArrayFromByteArray(stream.GetBuffer());
    }

    public float[] FloatArrayFromByteArray(byte[] input)
    {
        float[] output = new float[input.Length / 4];
        for (int i = 0; i < output.Length; i++)
        {
            output[i] = BitConverter.ToSingle(input, i * 4);
        }
        return output;
    }      
4

1 回答 1

1

我的第一个想法是,您正在绘制一个输出列多于输入列的图像,这将为您提供超出范围的minmax(因此yMin和)值。yMax我希望yMin在这种情况下计算会引发异常。

您应该将yMinandyMax值限制为画布上绘图区域的大小,然后BORDER_WIDTH在调用之前(或期间)添加偏移量g.DrawLine

于 2013-09-23T03:16:55.013 回答