我正在使用NAudio将一个完整的专辑分割成几个音频文件。该程序运行流畅,没有异常,但最终,输出的音频文件是不能收听的,它们显示为0秒。
下面是我的代码;albumPath描述存储单个文件的文件夹的路径,filePath是输入文件的路径。
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;
}
}
}
}我以前从来没有处理过音频文件,我也不知道比特率之类的东西。如果你有什么想法或建议,请告诉我,因为我被困在这里了。
发布于 2019-11-18 19:47:41
您需要对WAV报头的WaveFileWriter执行Dispose操作才能正确格式化。
更新您的splitWav方法:
using(WaveFileWriter writer = new WaveFileWriter(trackPath, reader.WaveFormat))
{
// your code here
}此外,您需要使用Write方法而不是WriteAsync方法,因为Write将跟踪写入数据块的字节数
https://stackoverflow.com/questions/58904923
复制相似问题