c# - 修剪音频文件(.wav、.mp3)

标签 c#

<分区>

我正在实现一个与使用用户指定的标记修剪音频文件相关的软件,例如,如果音频文件播放了 1 分钟,而用户想要将该文件从 20 秒修剪到 40 秒并将其保存为一个新文件。代码示例将不胜感激。

提前致谢。

最佳答案

感谢大家的回复,但我从 Mark Heath NAudio 那里得到了解决方案。这是示例 希望对您有所帮助:)

public static class WavFileUtils
{
    public static void TrimWavFile(string inPath, string outPath, TimeSpan cutFromStart, TimeSpan cutFromEnd)
    {
        using (WaveFileReader reader = new WaveFileReader(inPath))
        {
            using (WaveFileWriter writer = new WaveFileWriter(outPath, reader.WaveFormat))
            {
                int bytesPerMillisecond = reader.WaveFormat.AverageBytesPerSecond / 1000;

                int startPos = (int)cutFromStart.TotalMilliseconds * bytesPerMillisecond;
                startPos = startPos - startPos % reader.WaveFormat.BlockAlign;

                int endBytes = (int)cutFromEnd.TotalMilliseconds * bytesPerMillisecond;
                endBytes = endBytes - endBytes % reader.WaveFormat.BlockAlign;
                int endPos = (int)reader.Length - endBytes; 

                TrimWavFile(reader, writer, startPos, endPos);
            }
        }
    }

    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.WriteData(buffer, 0, bytesRead);
                }
            }
        }
    }
}

关于c# - 修剪音频文件(.wav、.mp3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6465863/

相关文章:

c# - 如何在 WinForm 上绘制 eclipse 刻的 3D 线?

c# - 如何访问 Windows.Storage 命名空间?

c# - WCF:无法满足对安全 token 的请求,因为身份验证失败

C# StreamReader 可以检查当前行号吗?

c# - 字典 .Values 和 .Keys 到数组(顺序相同)

c# - 为什么对单例使用 Lazy<T> 而不是静态工厂类?

c# - 有什么快速方法可以将简单的身份验证添加到一些 ASP.NET MVC 路由,而无需实现整个成员(member)提供程序 jazz?

c# - 在 IIS-10 中发布后,ASP.NET Core MVC 2.1.0 session 不工作

javascript - 允许 System.Windows.Forms.WebBrowser 运行 javascript

c# - 在 C# 中使用 String.Format 格式化字符串的问题