c# 根据语音文件画波形

c#对于语音的操作,必然离不开NAudio了,直接NuGet安装NAudio。

效果图如下:

c# 根据语音文件画波形_第1张图片

核心代码:首先通过AudioFileReader获取到音频数据byte[],再将byte[]转换为float[]数据,就可以根据float画波形了。

        /// 
        /// 开始画波形
        /// 
        /// 
        public void BeginDrawWaveLine(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                return;
            lineData.Clear();
            _audioFileReader = new AudioFileReader(fileName);
            byte[] datas = new byte[_audioFileReader.Length];
            _audioFileReader.Read(datas, 0, datas.Length);
            float[] wavdata = new float[datas.Length / sizeof(float)];
            Buffer.BlockCopy(datas, 0, wavdata, 0, datas.Length);
            var ww = mainCanvas.ActualWidth;
            var yScale = mainCanvas.ActualHeight / 2;
            double x, y1, y2;
            int index = wavdata.Length / (int)ww;
            for (int i = 0; i < ww; i++)
            {
                x = i;
                y1 = yScale - wavdata[i * index] * yScale;
                y2 = yScale + wavdata[i * index] * yScale;
                lineData.Add(new Point(x, y1));
                lineData.Add(new Point(x, y2));

            }
            this.InvalidateVisual();
        }
        ///
        /// 重写渲染方法
        /// 
        /// 
        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);
            if (lineData.Count > 1)
            {
                for (int i = 0; i < lineData.Count - 2; i++)
                {
                    drawingContext.DrawLine(pen, lineData[i], lineData[i + 1]);
                }
            }
        }

附完整项目代码下载:

https://download.csdn.net/download/esiangchioa/12545388

你可能感兴趣的:(C#)