首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NAudio拆分wav文件产生0秒wav文件

NAudio拆分wav文件产生0秒wav文件
EN

Stack Overflow用户
提问于 2019-11-18 04:29:48
回答 1查看 137关注 0票数 0

我正在使用NAudio将一个完整的专辑分割成几个音频文件。该程序运行流畅,没有异常,但最终,输出的音频文件是不能收听的,它们显示为0秒。

下面是我的代码;albumPath描述存储单个文件的文件夹的路径,filePath是输入文件的路径。

代码语言:javascript
复制
        private void splitWavPrep(string albumPath,string filePath)
    {

        MediaFoundationReader reader = new MediaFoundationReader(filePath);
        int bytesPerMilliSecond = reader.WaveFormat.AverageBytesPerSecond / 1000;
        for (int i = 0; i < tracks.Count; i++)
        {
            string trackName = tracks[i].Name;
            int startMilliSeconds = (int) tracks[i].StartSeconds * 1000;
            int duration;
            if (i< tracks.Count - 1)
            {
                //if there's a next track
                duration = (int)(tracks[i + 1].StartSeconds*1000) - startMilliSeconds;
            }
            else
            {
                //this is the last track
                duration = (int) reader.TotalTime.TotalMilliseconds - startMilliSeconds;
            }
            int startPos = startMilliSeconds * bytesPerMilliSecond;
            startPos = startPos - startPos % reader.WaveFormat.BlockAlign;
            int endMilliSeconds = startMilliSeconds + duration;
            int endBytes = (endMilliSeconds - startMilliSeconds) * bytesPerMilliSecond;
            endBytes = endBytes - endBytes % reader.WaveFormat.BlockAlign;

            int endPos = startPos + endBytes;

            string trackPath = Path.Combine(albumPath, trackName + ".wav");
            splitWav(trackPath, startPos, endPos, reader);

        }
    }

    private async void splitWav(string trackPath, int startPos, int endPos, MediaFoundationReader reader)
    {

        int progress = 0;
        WaveFileWriter writer = new WaveFileWriter(trackPath, reader.WaveFormat); 
        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)
                {
                    await writer.WriteAsync(buffer, 0, bytesRead);
                    progress += bytesRead;
                }
            }
        }
    }

我以前从来没有处理过音频文件,我也不知道比特率之类的东西。如果你有什么想法或建议,请告诉我,因为我被困在这里了。

EN

回答 1

Stack Overflow用户

发布于 2019-11-18 19:47:41

您需要对WAV报头的WaveFileWriter执行Dispose操作才能正确格式化。

更新您的splitWav方法:

代码语言:javascript
复制
using(WaveFileWriter writer = new WaveFileWriter(trackPath, reader.WaveFormat)) 
{
   // your code here
}

此外,您需要使用Write方法而不是WriteAsync方法,因为Write将跟踪写入数据块的字节数

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58904923

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档