Search code examples
c#wpfmp3naudio

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. I am developing in 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);
  }
}

Solution

  • Use a MemoryStream instead of FileStream's. 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[])).