简体   繁体   English

Naudio 如何在 byte[] 变量中播放 MP3

[英]Naudio How to play a MP3 in a byte[] variable

I read a Mp3 Sound from a database and I save it in a byte[] variable, I can save the byte in a file and play it, but I want to play the file directly without save the file in the disk.我从数据库中读取 Mp3 声音并将其保存在 byte[] 变量中,我可以将字节保存在文件中并播放它,但我想直接播放文件而不将文件保存在磁盘中。 I am developing in WPF.我正在开发 WPF。

byte[] array = Word_Sounds_DB.Records[0].Sound1;
FileStream fs = new FileStream("a.mp3",FileMode.Create);
{
  fs.Write(array, 0, array.Length);
}
fs.Close();
using (var ms = File.OpenRead("a.mp3"))
using (var rdr = new Mp3FileReader(ms))
using (var wavStream = WaveFormatConversionStream.CreatePcmStream(rdr))
using (var baStream = new BlockAlignReductionStream(wavStream))
using (var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()))
{
  waveOut.Init(baStream);
  waveOut.Play();
  while (waveOut.PlaybackState == PlaybackState.Playing)
  {
    Thread.Sleep(100);
  }
}

Use a MemoryStream instead of FileStream's.使用MemoryStream而不是 FileStream。 Also pay attention to MemoryStream 's read/write position after setting it up for consumption by NAudio (see here for some related info: memorystream(byte[]) vs memorystream.write(byte[]) ).还要注意MemoryStream的读/写 position 设置后供 NAudio 使用(有关一些相关信息,请参见此处: memorystream(byte[]) vs memorystream.write(byte[]) )。

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

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