c# - 开源C#代码来呈现波形?

标签 c# audio

是否有任何开源 C# 代码或库来呈现给定字节数组的图形波形?

最佳答案

这是开源的:

public static void DrawNormalizedAudio(ref float[] data, PictureBox pb,
    Color color)
{
    Bitmap bmp;
    if (pb.Image == null)
    {
        bmp = new Bitmap(pb.Width, pb.Height);
    }
    else
    {
        bmp = (Bitmap)pb.Image;
    }

    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);
        }
    }
    pb.Image = bmp;
}

这个函数会产生这样的结果:

enter image description here

这采用浮点格式的样本数组(其中所有样本值的范围从 -1 到 +1)。如果您的原始数据实际上是 byte[] 数组的形式,您将需要做一些工作才能将其转换为 float[]。如果您也需要,请告诉我。

更新:由于这个问题在技术上要求提供一些东西来呈现字节数组,这里有几个辅助方法:

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;
}

更新 2:我忘了有更好的方法来做到这一点:

public float[] FloatArrayFromByteArray(byte[] input)
{
    float[] output = new float[input.Length / 4];
    Buffer.BlockCopy(input, 0, output, 0, input.Length);
    return output;
}

我想我就是太喜欢 for 循环了。

关于c# - 开源C#代码来呈现波形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1215326/

相关文章:

c++ - 解码 Opus 音频数据

c# - 剪贴板始终为空

c# - Action 回调与 for 循环冲突

c# - 如何检查 C# 中的库 (dll) 是否可用?

c# - C# 中是否有 List<T> 的方法,例如在 c++ 中为 vector<T> 调整大小

ios - iOS Xcode 6-Segues不起作用

c# - Linq 到数据集

swift - Google Nearby for Swift - 如何仅发现音频?

javascript - 如何避免在wavesurfer js中创建多个区域

vb.net - 将音频文件从 Windows 窗体应用程序资源复制到硬盘驱动器