我想使用 NET 提供的System.Media.SoundPlayer机制播放从网上下载的 MP3 文件。由于它适用于 WAV 格式,它需要例如NAudio库的支持——我需要将 MP3 转换为 WAV。
我想在内存中进行所有操作,因为我需要它被称为快速,但我有问题。下面我展示了按预期工作的代码,但它与文件协作。相反,我只需要使用内存操作使其工作。
(1) 有效,但涉及磁盘操作:
public void Speak(Uri mp3FileUri)
{
using (var client = new WebClient())
{
using (var networkStream = client.OpenRead(mp3FileUri))
{
if (networkStream != null)
{
var temp = Path.GetTempPath();
var mp3File = Path.Combine(temp, "file.mp3");
var wavFile = Path.Combine(temp, "file.wav");
using (var fileStream = File.Create(mp3File))
{
networkStream.CopyTo(fileStream);
}
using (var reader = new Mp3FileReader(mp3File))
{
WaveFileWriter.CreateWaveFile(wavFile, reader);
}
using(var player = new SoundPlayer(wavFile))
{
player.Play();
}
}
}
}
}
(2) 不起作用 - 不抛出异常,但不播放任何内容:
public void Speak(Uri mp3FileUri)
{
using (var client = new WebClient())
{
using (var networkStream = client.OpenRead(mp3FileUri))
{
if (networkStream != null)
{
var memStream = new MemoryStream();
networkStream.CopyTo(memStream);
memStream.Position = 0;
using (var reader = new Mp3FileReader(memStream))
{
var outStream = new MemoryStream();
using (var writer = new WaveFileWriter(outStream, reader.WaveFormat))
{
var num = 0L;
var buffer = new byte[reader.WaveFormat.AverageBytesPerSecond * 4];
while (true)
{
var count = reader.Read(buffer, 0, buffer.Length);
if (count != 0)
{
num += count;
if (num <= int.MaxValue)
writer.Write(buffer, 0, count);
else
throw new InvalidOperationException("Too large file or endless stream.");
}
else
break;
}
writer.Flush();
outStream.Position = 0;
using(var player = new SoundPlayer(outStream))
{
player.Play(); /* why silence ? */
}
}
}
}
}
}
}
怎么做?第二个代码示例有什么问题?