【问题标题】:Generate wave image like sound cloud c#生成像声音云一样的波形c#
【发布时间】:2013-09-25 23:03:01
【问题描述】:

当我尝试通过将 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;
    }      

【问题讨论】:

    标签: c#-4.0 naudio waveform


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 2010-11-08
      相关资源
      最近更新 更多