简体   繁体   English

如何使用 NAudio/SoundTouch 在 ASP.NET MVC 5 中流式传输 MP3?

[英]How to use NAudio/SoundTouch to stream MP3 in ASP.NET MVC 5?

I am completely new to working with audio.我对使用音频完全陌生。 I eventually want to stream an MP3 to a web page and allow user to alter the tempo.我最终想将 MP3 流式传输到网页并允许用户更改速度。 I got a HTML5 audio element set up and it can stream a MP3 fine.我设置了一个 HTML5 音频元素,它可以很好地流式传输 MP3。 I can import the MP3 into NAudio.AudioFileReader and stream that to the page and that also works fine using the following code:我可以将 MP3 导入NAudio.AudioFileReader并将其流式传输到页面,使用以下代码也可以正常工作:

string fn = Server.MapPath("~/Uploads/Music/" + filename);
AudioFileReader reader = new AudioFileReader(fn);
MemoryStream outputStream = new MemoryStream();

using (NAudio.Wave.WaveFileWriter waveFileWriter = new WaveFileWriter(outputStream, reader.WaveFormat))
{
    byte[] bytes = new byte[reader.Length];
    reader.Position = 0;
    reader.Read(bytes, 0, (int)reader.Length);
    waveFileWriter.Write(bytes, 0, bytes.Length);
    waveFileWriter.Flush();
}

return File(outputStream.ToArray(), "audio/mp3");

I'm not even sure if this is the proper way to do this, but I modified some code I found online and this does work.我什至不确定这是否是正确的方法,但我修改了一些我在网上找到的代码,这确实有效。 However, when looking at the NAudio Varispeed demo which integrates the SoundTouch library and trying to incorporate it, it no longer works.但是,当查看集成了 SoundTouch 库并尝试合并它的 NAudio Varispeed 演示时,它不再起作用。

I modified my code like this:我像这样修改了我的代码:

string fn = Server.MapPath("~/Uploads/Music/" + filename);
AudioFileReader reader = new AudioFileReader(fn);
bool useTempo = true;
VarispeedSampleProvider speedControl = new VarispeedSampleProvider(reader, 100, new SoundTouchProfile(useTempo, false));
MemoryStream outputStream = new MemoryStream();

using (NAudio.Wave.WaveFileWriter waveFileWriter = new WaveFileWriter(outputStream, reader.WaveFormat))
{
    byte[] bytes = new byte[reader.Length];
    speedControl.Read(bytes.Select(b => (float)Convert.ToDouble(b)).ToArray(), 0, (int)reader.Length);
    waveFileWriter.Write(bytes, 0, bytes.Length);
    waveFileWriter.Flush();
}

return File(outputStream.ToArray(), "audio/mp3");

It builds and appears like it's working but when I hit play, I get no audio.它构建并看起来像它在工作,但是当我点击播放时,我没有音频。 What am I doing wrong here?我在这里做错了什么? Is this not even a good way to accomplish what I want?这甚至不是实现我想要的东西的好方法吗?

You are reading into a temporary array (created by ToArray ), so the audio you read is lost.您正在读取一个临时数组(由ToArray创建),因此您读取的音频丢失。

Instead, declare a float[] , read into that, and then write the contents of that into the waveFileWriter .相反,声明一个float[] ,读入它,然后将其内容写入waveFileWriter

Also, it is very important to use the return value from Read which will indicate the number of samples actually written into the array.此外,使用Read的返回值非常重要,该值将指示实际写入数组的样本数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM