iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >C#基于NAudio怎么实现对Wav音频文件剪切
  • 286
分享到

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

2023-06-21 21:06:19 286人浏览 安东尼
摘要

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

这篇文章主要讲解了“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    {        /// <summary>        /// 基于NAudio工具对Wav音频文件剪切(限PCM格式)        /// </summary>        /// <param name="inPath">目标文件</param>        /// <param name="outPath">输出文件</param>        /// <param name="cutFromStart">开始时间</param>        /// <param name="cutFromEnd">结束时间</param>        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);                }            }        }        /// <summary>        /// 重新合并wav文件        /// </summary>        /// <param name="reader">读取流</param>        /// <param name="writer">写入流</param>        /// <param name="startPos">开始流</param>        /// <param name="endPos">结束流</param>        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    {        /// <summary>        /// 获取时间戳        /// </summary>        /// <returns></returns>        public static string GetTimeStamp()        {            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);            return Convert.ToInt64(ts.TotalMilliseconds).ToString();        }        /// <summary>        /// 返回音频时长        /// </summary>        /// <param name="SongPath">音频文件路径</param>        /// <returns></returns>        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;        }      /// <summary>        /// 时间格式转毫秒值        /// </summary>        /// <param name="time">时间字符串</param>        /// <returns></returns>        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#基于NAudio怎么实现对Wav音频文件剪切这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

--结束END--

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

本文链接: https://www.lsjlt.com/news/300830.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • C++ 生态系统中流行库和框架的贡献指南
    作为 c++++ 开发人员,通过遵循以下步骤即可为流行库和框架做出贡献:选择一个项目并熟悉其代码库。在 issue 跟踪器中寻找适合初学者的问题。创建一个新分支,实现修复并添加测试。提交...
    99+
    2024-05-14
    框架 c++ 流行库 git
  • C++ 生态系统中流行库和框架的社区支持情况
    c++++生态系统中流行库和框架的社区支持情况:boost:活跃的社区提供广泛的文档、教程和讨论区,确保持续的维护和更新。qt:庞大的社区提供丰富的文档、示例和论坛,积极参与开发和维护。...
    99+
    2024-05-14
    生态系统 社区支持 c++ overflow 标准库
  • c++中if elseif使用规则
    c++ 中 if-else if 语句的使用规则为:语法:if (条件1) { // 执行代码块 1} else if (条件 2) { // 执行代码块 2}// ...else ...
    99+
    2024-05-14
    c++
  • c++中的继承怎么写
    继承是一种允许类从现有类派生并访问其成员的强大机制。在 c++ 中,继承类型包括:单继承:一个子类从一个基类继承。多继承:一个子类从多个基类继承。层次继承:多个子类从同一个基类继承。多层...
    99+
    2024-05-14
    c++
  • c++中如何使用类和对象掌握目标
    在 c++ 中创建类和对象:使用 class 关键字定义类,包含数据成员和方法。使用对象名称和类名称创建对象。访问权限包括:公有、受保护和私有。数据成员是类的变量,每个对象拥有自己的副本...
    99+
    2024-05-14
    c++
  • c++中优先级是什么意思
    c++ 中的优先级规则:优先级高的操作符先执行,相同优先级的从左到右执行,括号可改变执行顺序。操作符优先级表包含从最高到最低的优先级列表,其中赋值运算符具有最低优先级。通过了解优先级,可...
    99+
    2024-05-14
    c++
  • c++中a+是什么意思
    c++ 中的 a+ 运算符表示自增运算符,用于将变量递增 1 并将结果存储在同一变量中。语法为 a++,用法包括循环和计数器。它可与后置递增运算符 ++a 交换使用,后者在表达式求值后递...
    99+
    2024-05-14
    c++
  • c++中a.b什么意思
    c++kquote>“a.b”表示对象“a”的成员“b”,用于访问对象成员,可用“对象名.成员名”的语法。它还可以用于访问嵌套成员,如“对象名.嵌套成员名.成员名”的语法。 c++...
    99+
    2024-05-14
    c++
  • C++ 并发编程库的优缺点
    c++++ 提供了多种并发编程库,满足不同场景下的需求。线程库 (std::thread) 易于使用但开销大;异步库 (std::async) 可异步执行任务,但 api 复杂;协程库 ...
    99+
    2024-05-14
    c++ 并发编程
  • 如何在 Golang 中备份数据库?
    在 golang 中备份数据库对于保护数据至关重要。可以使用标准库中的 database/sql 包,或第三方包如 github.com/go-sql-driver/mysql。具体步骤...
    99+
    2024-05-14
    golang 数据库备份 mysql git 标准库
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作