千家信息网

C#基于NAudio怎么实现对Wav音频文件剪切

发表于:2026-11-04 作者:千家信息网编辑
千家信息网最后更新 2026年11月04日,这篇文章主要讲解了"C#基于NAudio怎么实现对Wav音频文件剪切",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"C#基于NAudio怎么实现对Wav
千家信息网最后更新 2026年11月04日C#基于NAudio怎么实现对Wav音频文件剪切

这篇文章主要讲解了"C#基于NAudio怎么实现对Wav音频文件剪切",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"C#基于NAudio怎么实现对Wav音频文件剪切"吧!

前言

C#基于NAudio工具对Wav音频文件进行剪切,将一个音频文件剪切成多个音频文件

注:调用方法前需要导入NAudio.dll或者在NuGet程序管理器搜索NAudio并安装

本文是按时间剪切

实现代码

using NAudio.Wave;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace XXX.util{    public static class WavFileUtils    {        ///         /// 基于NAudio工具对Wav音频文件剪切(限PCM格式)        ///         /// 目标文件        /// 输出文件        /// 开始时间        /// 结束时间        public static void TrimWavFile(string inPath, string outPath, TimeSpan cutFromStart, TimeSpan cutFromEnd)        {            using (WaveFileReader reader = new WaveFileReader(inPath))            {                int fileLength = (int)reader.Length;using (WaveFileWriter writer = new WaveFileWriter(outPath, reader.WaveFormat))                {                    float bytesPerMillisecond = reader.WaveFormat.AverageBytesPerSecond / 1000f;                    int startPos = (int)Math.Round(cutFromStart.TotalMilliseconds * bytesPerMillisecond);                    startPos = startPos - startPos % reader.WaveFormat.BlockAlign;                    int endPos = (int)Math.Round(cutFromEnd.TotalMilliseconds * bytesPerMillisecond);                    endPos = endPos - endPos % reader.WaveFormat.BlockAlign;                    //判断结束位置是否越界                    endPos = endPos > fileLength ? fileLength : endPos;                    TrimWavFile(reader, writer, startPos, endPos);                }            }        }        ///         /// 重新合并wav文件        ///         /// 读取流        /// 写入流        /// 开始流        /// 结束流        private static void TrimWavFile(WaveFileReader reader, WaveFileWriter writer, int startPos, int endPos)        {            reader.Position = startPos;            byte[] buffer = new byte[1024];            while (reader.Position < endPos)            {                int bytesRequired = (int)(endPos - reader.Position);                if (bytesRequired > 0)                {                    int bytesToRead = Math.Min(bytesRequired, buffer.Length);                    int bytesRead = reader.Read(buffer, 0, bytesToRead);                    if (bytesRead > 0)                    {                        writer.Write(buffer, 0, bytesRead);                    }                }            }        }    }}

调用:

string filePath = "D:\\wav\\test.wav";//需要切割的文件路径int cutTimeSpan = 20;//切割的时间片段时间(秒)FileInfo fi = new FileInfo(filePath);//获取录音文件时长(秒)int fileTime = (int)Util.Cover(Util.GetVoiceTime(filePath)) / 1000;//计算文件需要切割多少等份decimal fileNum = Math.Ceiling((decimal)fileTime / cutTimeSpan);int i = 0;while (i < fileNum){    string nowTime = Util.GetTimeStamp();//当前时间戳    //切割后保存的文件绝对地址    var outputPath = System.IO.Path.Combine(fi.Directory.FullName, string.Format("{0}_{1}{2}", fi.Name.Replace(fi.Extension, ""), nowTime, fi.Extension));    //切割的开始时间    TimeSpan cutFromStart = TimeSpan.FromSeconds(i * cutTimeSpan);    //切割的结束时间    TimeSpan cutFromEnd = cutFromStart + TimeSpan.FromSeconds(cutTimeSpan);    //音频切割    WavFileUtils.TrimWavFile(recordFile.FilePath, outputPath, cutFromStart, cutFromEnd);    i++;}

Util 类:

using Shell32;using System;using System.Diagnostics;using System.IO;using System.Net;using System.Net.Sockets;using System.Text.RegularExpressions;using System.Threading;using System.Windows.Forms;namespace XXX.util{    class Util    {        ///         /// 获取时间戳        ///         ///         public static string GetTimeStamp()        {            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);            return Convert.ToInt64(ts.TotalMilliseconds).ToString();        }        ///         /// 返回音频时长        ///         /// 音频文件路径        ///         public static string GetVoiceTime(string SongPath)        {            string dirName = Path.GetDirectoryName(SongPath);            string SongName = Path.GetFileName(SongPath);            ShellClass sh = new ShellClass();            Folder dir = sh.NameSpace(dirName);            FolderItem item = dir.ParseName(SongName);            string SongTime = Regex.Match(dir.GetDetailsOf(item, -1), "\\d:\\d{2}:\\d{2}").Value;//返回音频时长            return SongTime;        }      ///         /// 时间格式转毫秒值        ///         /// 时间字符串        ///         public static long Cover(string time)        {            string[] a = time.Split(':');            if (long.Parse(a[0]) == 0 && long.Parse(a[1]) == 0)            {                return long.Parse(a[2]) * 1000;            }            else if (long.Parse(a[0]) == 0 && long.Parse(a[1]) != 0)            {                return (long.Parse(a[1]) * 60 + long.Parse(a[2])) * 1000;            }            else if (long.Parse(a[0]) != 0 && long.Parse(a[1]) == 0)            {                return ((long.Parse(a[0]) * 60 * 60) + long.Parse(a[2])) * 1000;            }            else if (long.Parse(a[0]) != 0 && long.Parse(a[1]) != 0)            {                return (((long.Parse(a[0]) * 60) + long.Parse(a[1])) * 60) * 1000;            }            return 0;        }    }}

效果图

感谢各位的阅读,以上就是"C#基于NAudio怎么实现对Wav音频文件剪切"的内容了,经过本文的学习后,相信大家对C#基于NAudio怎么实现对Wav音频文件剪切这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!

文件 音频 时间 剪切 C# 时长 学习 内容 工具 格式 路径 代码 位置 前言 地址 多个 字符 字符串 就是 思路 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 互联网科技保险 金融科技还是互联网 睿民互联网科技 长亮科技 互联网金融 多迪互联网科技有限公司 顺网科技2021年互联网排名 安控科技rtu产品工业互联网 互联网科技公司需要的职位 昭通互联网科技选哪家 世界互联网领先科技成果获奖 黑科技 体验场景 互联网大会 江苏苏星互联网科技有限公司 电子商务与互联网科技的关系 工业互联网科技成果转化 图游互联网科技 承德科技产业互联网平台 安徽九吞吴互联网科技有限公司 重庆科技产业互联网有哪些 山东亿川互联网科技有限责任公司 互联网科技快速发展优美句子 亿人帮互联网科技有限公司 河南云网互联网络科技有限公司 中关村互联网 科技集团 互联网科技革命 互联网科技博客 恒生科技互联网指数分析 江阴互联网智能科技产品进口 崇明区互联网教育科技售后服务 银川新华互联网科技学校联系电话 互联网科技新闻
0