WebRTC API recording streaming data

I. Introduction

        In this blog , we introduced how to use WebRTC API to record local desktop data and play it through HTML video. Now we want to save the collected local desktop data recording as a file and download it locally, or record the data collected by audio and video equipment , you can use the MediaRecorder class.

        var mediaRecorder = new MediaRecorder(stream, options);

stream: Indicates the media stream parameter, which can be the stream parameter object obtained from getUserMedia or getDisplayMedia.

options: Indicates restriction options, which can contain the following attributes.

attribute value illustrate
mimeType The type of recording container, which can be video/webm;codecs=h264, audio/webm;codecs=opus
audioBitsPerSecond audio bit rate
videoBitsPerSecond Video bit rate
bitsPerSecond overall code rate

2. MediaRecorder

1. MediaRecorder recording related functions

MediaRecorder.isTypeSupported()

Description: Determine whether the parameters set in the restriction option are supported, for example, you can set mimeType to video/webm;codecs=h264.

MediaRecorder.start(timeslice)

Description: start recording, timeslice is an optional parameter, if set, the data will be stored by time slice.

MediaRecorder.stop()

Description: Stop recording, and the ondataavailable event will be triggered after calling stop.

MediaRecorder.pause()

Description: Pause recording.

MediaRecorder.resume()

Description: Resume recording.

2. MediaRecorder event

MediaRecorder.ondataavailable

Note: Calling back the event function indicates that there is valid data, and the data can be obtained through the data attribute of the callback event function parameter. If timeslice is specified in MediaRecorder.start, the ondataavailable event function will be triggered every timeslice period, if no timeslice is specified, the ondataavailable event function will be called back when stop is called.

MediaRecorder.onerror

Description: This function will be called back when an error occurs, and the recording will stop.

3. Example demonstration

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>录制本地桌面</title>
    </head>
    <body>
        <table>
            <tr>
                <td><video autoplay playsinline id="video_player"></video></td>
                <td><video autoplay playsinline id="record_video_player"></video></td>
            </tr>
        </table>
        <button id="record">开始录制</button>
        <button id="play" disabled>播放</button>
        <button id="download" disabled>下载到本地</button>
        <script src="./js/record_desktop.js"></script>
    </body>
</html>
'use strict'

var videoPlayer = document.querySelector("video#video_player");
var recordVideoPlayer = document.querySelector("video#record_video_player");
var btRecord = document.querySelector("button#record");
var btPlay = document.querySelector("button#play");
var btDownload = document.querySelector("button#download");

var dataBuffer;
var mediaRecorder;

function HandleError(err) {
    console.log(err.name + "," + err.message);
}

function GetMediaStream(mediaStream) {
    videoPlayer.srcObject = mediaStream;
    window.stream = mediaStream;
}

function HandleDataAvailable(event) {
    if(event && event.data && event.data.size > 0) {
        dataBuffer.push(event.data);
    }
}

function StartRecord() {
    var options = {
        mimeType : 'video/webm;codecs=h264'
    };
    dataBuffer = [];

    if (!MediaRecorder.isTypeSupported(options.mimeType)) {
        console.error(`${options.mimeType} is not supported!`);
        return;
    }

    try {
        mediaRecorder = new MediaRecorder(window.stream, options);
    } catch (err) {
        console.error('Fail to new MediaRecorder!');
        return;
    }
    mediaRecorder.ondataavailable = HandleDataAvailable;
    mediaRecorder.start();
}

function StopRecord() {
    mediaRecorder.stop();
}

if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
    console.log('getDisplayMedia is not supported!');
} else {
    var constraints = {
        video : {
            frameRate   : 24,
            width       : 640,
            height      : 480
        }
    };
    navigator.mediaDevices.getDisplayMedia(constraints)
        .then(GetMediaStream)
        .catch(HandleError);
}

btRecord.onclick = () => {
    if (btRecord.textContent === "开始录制") {
        StartRecord();
        btRecord.textContent = "结束录制";
        btPlay.disabled = true;
        btDownload.disabled = true;
    } else if (btRecord.textContent === "结束录制") {
        StopRecord();
        btRecord.textContent = "开始录制";
        btPlay.disabled = false;
        btDownload.disabled = false;
    }
}

btPlay.onclick = ()=> {
    var blob = new Blob(dataBuffer, {type : 'video/webm'});
    recordVideoPlayer.src = window.URL.createObjectURL(blob);
    recordVideoPlayer.srcObject = null;
    recordVideoPlayer.controls = true;
    recordVideoPlayer.play();
}

btDownload.onclick = ()=> {
    var blob = new Blob(dataBuffer, {type : 'video/webm'});
    var url = window.URL.createObjectURL(blob);
    var a = document.createElement('a');
    a.href = url;
    a.style.display = 'none';
    a.download = 'video.webm';
    a.click();
}

        The effect after running is as follows, first select the screen or window you want to share.

         Click the start recording button to start recording, and then click the stop recording button to end the recording, and then click the play button to play the desktop data collected during the recording, click download to the local to save the recorded desktop data as a file to the local.

Guess you like

Origin blog.csdn.net/weixin_38102771/article/details/123618358