0

I'm making a small application that receive data from another application and play the sound it receives parts by parts.

This is the simulation I'm doing:

        var soundPlayer = new  SoundPlayer();
        var buffer = new byte[2048];
        using (var fileStream = File.OpenRead(filePath))
        {
            var iOffset = 0;
            while (true)
            {
                try
                {
                    iOffset = fileStream.Read(buffer, iOffset, buffer.Length);
                    if (iOffset == 0)
                    {
                        Console.WriteLine("Offset end.");
                        break;
                    }

                    var memoryStream = new MemoryStream(buffer, 0, buffer.Length);
                    soundPlayer.Stream = memoryStream;
                    //soundPlayer.Load();
                    soundPlayer.Play();

                    Thread.Sleep(TimeSpan.FromSeconds(10));
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                    break;
                }
            }

It reads a file to memory stream parts by parts (2048 bytes per 5 seconds - connection delay simulation)

The application crashes without jumping into exception code block after soundPlayer.Play() method.

What wrong am I doing ?

Can anyone help me please ?

Thanks,

Redplane
  • 2,971
  • 4
  • 30
  • 59
  • What is the exception thrown? – Bitz Mar 20 '18 at 16:07
  • It crashed without jumping into exception – Redplane Mar 20 '18 at 16:16
  • Probably because you're not reading the entire file. When I run your code it gives that it tried to read or write in a protected memory. The wav header has a field that indicates the chunk size in bytes, so the player probably tries to read that amout of bytes, which is bigger than the stream size. – Magnetron Mar 20 '18 at 16:52

1 Answers1

0

I think that you can not use the SoundPlayer in that way. From the documentation of the SoundPlayer class:

A SoundPlayer configured to load a .wav file from a Stream or URL must load the .wav file into memory before playback begins.

If you want to be able to receive an audio stream in chunks you need to use another library. I can recommend NAudio. See also this SO post Play audio from a stream using C#.

Marius
  • 1,529
  • 6
  • 21