我试图在 Azure 网站(没有安装 ACM 或 DMO 编解码器)上使用 ASP.net 绘制波形,所以我不得不使用 NLayer 来读取 mp3 文件。我下面的代码与常规的 DmoMp3FrameDecompressor 完美配合,但是当我使用 NLayer 解压缩器时,它就不行了。
也许 NLayer 解压器的格式是 32bit Float 而不是 16bit PCM。
byte[] data = new WebClient().DownloadData(URL);
int maxAmplitude = 0;
short[,] dataArray = new short[Width, 2];
//using (Mp3FileReader wavestream = new Mp3FileReader(new MemoryStream(data), wf => new DmoMp3FrameDecompressor(wf)))
using (Mp3FileReader wavestream = new Mp3FileReader(new MemoryStream(data), new Mp3FileReader.FrameDecompressorBuilder(waveFormat => new NLayer.NAudioSupport.Mp3FrameDecompressor(waveFormat))))
{
WaveChannel32 channelStream = new WaveChannel32(wavestream);
int bytesPerSample = (wavestream.WaveFormat.BitsPerSample / 8) * channelStream.WaveFormat.Channels;
wavestream.Position = 0;
long lenSamples = wavestream.Length / bytesPerSample;
int samplesPerPixel = (int)(lenSamples / Width);
int bytesRead1;
byte[] waveData1 = new byte[samplesPerPixel * bytesPerSample];
// First get all the data
for (int x = 0; x < Width; x++)
{
short low = 0;
short high = 0;
bytesRead1 = wavestream.Read(waveData1, 0, samplesPerPixel * bytesPerSample);
if (bytesRead1 == 0)
break;
for (int n = 0; n < bytesRead1; n += 2)
{
short sample = BitConverter.ToInt16(waveData1, n);
if (sample < low) low = sample;
if (sample > high) high = sample;
}
if (-low > maxAmplitude) maxAmplitude = -low;
if (high > maxAmplitude) maxAmplitude = high;
dataArray[x, 0] = low;
dataArray[x, 1] = high;
}
}