我试图通过NAudio只读取mp3文件的数据,我使用WaveStream我要求WaveStream长度,并根据该长度分配byte []。当我尝试立即读取整个流并且结果是异常时: “附加信息:缓冲区空间不足”
using (Mp3FileReader fr = new Mp3FileReader(@"C:\Users\AmitL\Desktop\The Fabulous Thunderbirds - Powerful Stuff.mp3"))
{
byte[] buffer = new byte[2];
long l_lLen = fr.Length;
Console.WriteLine("mp3 length" + l_lLen.ToString());
using (WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(fr))
{
long l_lLenPCM = pcm.Length;
int l_dLenPCM = Convert.ToInt32(l_lLenPCM);
byte[] l_bData = new byte[l_dLenPCM];
Console.WriteLine("l_bData len: " + l_bData.Length.ToString());
Console.WriteLine("l_dLenPCM: " + l_dLenPCM.ToString());
Console.WriteLine("l_bData[l_bData.Length - 1]: " + l_bData[l_bData.Length - 1].ToString());
using (WaveStream aligned = new BlockAlignReductionStream(pcm))
{
Console.WriteLine("aligned.Length" + aligned.Length);
Console.WriteLine("aligned.Read: " + aligned.Read(l_bData, 0 , l_dLenPCM ));
}
}
}
outpout: mp3长度4377442 l_bData len:126074880 l_dLenPCM:126074880 l_bData [l_bData.Length - 1]:0 aligned.Length126074880
当我尝试在Iterations读取流时,它会在读取126074字节的382次迭代和另一次103924字节的最终读取之后停止读取... ???? 简单地替换我读到的行:
for (int i = 0; i < 500; i++)
{
Console.WriteLine("i: " + i.ToString() + "aligned.Read : " + aligned.Read(l_bData, (l_dLenPCM / 1000) * i, l_dLenPCM / 1000));
}
任何人都知道我做错了什么?
答案 0 :(得分:1)
首先,不需要将WaveFormatConversionStream
或BlockAlignReductionStream
与Mp3FileReader
一起使用。只需拨打Read
即可获得PCM
其次,不要一次尝试读取整个MP3文件,因为数据必须通过编解码器传递,编解码器可能具有有限的缓冲区大小。而是在循环中调用Read
,直到它返回0表示文件结束。一次一秒是确定Read
缓冲区大小的好经验法则。您可以使用AverageBytesPerSecond
WaveFormat
的{{1}}属性来获取此字节大小。