0

I try to create an endpoint which delivers a live stream of my webcam. I´m using AForge to access the camera, but I can´t manage to create and return a stream that actually renders in a video tag in the html client.

Additionally: The MemoryStream I’m using growes every second. And that is definitly not what I want.

What I tried so far:

Cam.cs:

public class Cam
{
    MemoryStream stream = new MemoryStream();

    public Cam()
    {
        FilterInfoCollection videoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
        VideoCaptureDevice finalVideo = new VideoCaptureDevice(videoCaptureDevices[0].MonikerString);
        finalVideo.NewFrame += this._streamNewFrame;
        finalVideo.Start();
    }

    private void _streamNewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
    {
        System.Drawing.Image imgforms = (Bitmap)eventArgs.Frame.Clone();


        imgforms.Save(this.stream, ImageFormat.Bmp);

        this.stream.Seek(0, SeekOrigin.Begin);
    }

    public Stream GetStream()
    {
        MemoryStream stream = new MemoryStream();
        this.stream.CopyTo(stream);
        return stream;
    }
}

CamController.cs:

[ApiController]
[Route("[controller]")]
public class CamController : ControllerBase
{
    private readonly Cam cam;

    public CamController(Cam cam)
    {
        this.cam = cam;
    }

    [HttpGet]
    public IActionResult Get()
    {
        var contentType = "multipart/x-mixed-replace;boundary=myboundary";
        Stream stream = this.cam.GetStream();
        var result = new FileStreamResult(stream, contentType)
        {
            EnableRangeProcessing = true,
            
        };
        return result;
    }
}
Anonymous Asked question May 14, 2021