sskodje / ScreenRecorderLib

A .NET library for screen recording in Windows, using native Microsoft Media Foundation for realtime encoding to h264 video or PNG images.
MIT License
414 stars 94 forks source link

Get MP4 STREAMING #194

Closed Riton2013 closed 2 years ago

Riton2013 commented 2 years ago

Hi, I need to get MP4 streaming on Recorder Callback, what should I do? Thank you very much for your sharing!

sskodje commented 2 years ago

If you want to access the data while recording, you need to create your own stream that can write and seek and pass it to the recorder. Here's an example that wraps a File stream and writes to it, but you can modify it to do whatever you want with the data, like sending it over a network.

Note that you need to enable fragmented MP4 in order for this to work, like this

            var opts = new RecorderOptions
            {
                VideoEncoderOptions = new VideoEncoderOptions
                {
                    IsFragmentedMp4Enabled = true
                }
            };

            using (Recorder rec = Recorder.CreateRecorder(opts))
            { 
                FileStream fs = File.Create("a file path..");
                using (CustomStream stream = new CustomStream (fs))
                {
                  rec.Record(stream);
                }
            }
    public class CustomStream : Stream
    {
        private FileStream _fileStream;
        public WebStream(FileStream fileStream)
        {
            _fileStream = fileStream;
        }

        public override bool CanRead => false;

        public override bool CanSeek => true;

        public override bool CanWrite => true;

        public override long Length => 0;

        public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

        public override void Flush()
        {
            _fileStream.Flush();
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            throw new NotImplementedException();
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
             return offset;
        }

        public override void SetLength(long value)
        {

        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            _fileStream.Write(buffer, offset, count);
            //Here you can instead do whatever you want with the data, 
            //but don't perform too much work or blocking I/O in the Write method or the recording will be choppy.
        }
    }
Riton2013 commented 2 years ago

Thank you very much!!

Riton2013 commented 2 years ago

Another question: The data I get form buffer is already decode by H264 right?

sskodje commented 2 years ago

Yes