我需要根据多个音频文件(.wav / .mp3)生成波形。我目前正在使用NAudio,但我遇到了一些问题。我不能使用文件的路径,因为我不允许将文件上传到服务器,大多数浏览器阻止路径(安全原因),所以我的方法是使用流或内存流。我发现这个project做了一些非常相似的事情,但是如果没有文件的直接路径,我就无法让它工作。 这是我从用户那里获取文件的代码
[HttpPost]
public ActionResult UploadAudioFile()
{
if (Request.Files.Count > 0)
{
List<MusicViewModel> list = new List<MusicViewModel>();
var supportedFileTypes = new[] { "audio/mp3", "audio/wav" };
foreach (string file in Request.Files)
{
var _file = Request.Files[file];
if (_file != null)
{
var contentType = _file.ContentType.ToLower();
if (supportedFileTypes.Contains(contentType))
{
var s = _file.InputStream;
var name = _file.FileName;
var song = new MusicViewModel();
System.Drawing.Image img;
if (contentType.Equals("audio/mp3"))
{
song = _musicRepo.GetMetaDataFromMp3File(s, name);
img = _musicRepo.GenerateWaveForm(s);
}
else if (contentType.Equals("audio/wav"))
{
song = _musicRepo.GetMetaDataFromWavFile(s, name);
img = _musicRepo.GenerateWaveForm(s);
}
if (song != null)
{
list.Add(song);
}
}
else
{
return Json(new { isSuccess = false, errorMsg = "We only allow audio files of .mp3 or .wav format. You have attempted to upload a file with " + contentType + "." });
}
}
}
return Json(new { isSuccess = true, musicList = list });
}
return Json(new { isSuccess = false });
}
然后在我的音乐库中使用GenerateWaveForm
public Image GenerateWaveForm(Stream stream)
{
Image img = null;
WaveFormRenderer wr = new WaveFormRenderer();
try
{
img = wr.Render(stream);
}
catch (Exception ex)
{
throw;
}
return img;
}
我正在按照此class的方法,但我收到错误“不是WAVE文件 - 没有RIFF标题”。这是我创建异常的类
public Image Render(Stream stream)
{
int destBytesPerSample = 0;
long samples;
WaveStream readerStream = new WaveFileReader(stream);
if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm && readerStream.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat)
{
readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream);
readerStream = new BlockAlignReductionStream(readerStream);
var sourceBytesPerSample = (readerStream.WaveFormat.BitsPerSample / 8) * readerStream.WaveFormat.Channels;
SampleChannel sampleChannel = new SampleChannel(readerStream, false);
destBytesPerSample = 4 * sampleChannel.WaveFormat.Channels;
samples = destBytesPerSample * (readerStream.Length / sourceBytesPerSample);
var peakProvider = getPeakProvider();
WaveFormRendererSettings settings = GetRendererSettings();
var samplesPerPixel = (int)(samples / settings.Width);
var stepSize = settings.PixelsPerPeak + settings.SpacerPixels;
//peakProvider.Init(reader, samplesPerPixel * stepSize);
return Render(peakProvider, settings);
}
return null;
}
当我尝试在方法Render
中的第3行中创建对象readerStream时发生异常