Listening start event

  • EventTarget. AddEventListener () method specifies the listeners registered on the EventTarget, when the object trigger event is specified, the specified callback function will be executed. Event targets can be elements on a Document, such as Element,Document, or Window, or any other event-supporting object (such as XMLHttpRequest).

  • AddEventListener () works by adding the function or object that implements EventListener to the list of event listeners of the specified event type on the EventTarget that calls it.

document.querySelector('button#start').addEventListener('click', async () => {
    document.querySelector('button#start').disabled = true;
    const constraints = {
        audio: {},
        video: {
            width: 1280, height: 720
        }
    };
    await init(constraints);
});
Copy the code

Get audio and video tracks

  • MediaDevices. GetUserMedia () will prompt the user for permission to use the media input media input will produce a MediaStream, containing the request of the orbit of media types. This stream can contain A video track (from hardware or virtual video sources, such as cameras, video capture devices, screen sharing services, and so on), an audio track (also from hardware or virtual audio sources, such as microphones, A/D converters, and so on), or some other track type.

  • It returns a Promise object, and on success resolve calls back a MediaStream object. If the user denies permission, or if the desired media source is not available, Promise calls back a PermissionDeniedError or NotFoundError.

async function init(constraints) { try { const stream = await navigator.mediaDevices.getUserMedia(constraints); handleSuccess(stream); } catch (e) { console.error('navigator.getUserMedia error:', e); }}Copy the code
  • HTMLMediaElementOf the interfacesrcObjectProperty sets or returns an object that provides an andHTMLMediaElementThe associated media source, this object is usuallyMediaStream, but according to the specification it can beMediaSource.BloborFile.
function handleSuccess(stream) {
    recordButton.disabled = false;
    window.stream = stream;
    const gumVideo = document.querySelector('video#gum');
    gumVideo.srcObject = stream;
}
Copy the code

Recording a media stream

  • The MediaRecorder() constructor creates a MediaRecorder object that records the specified MediaStream

  • MediaRecorder. Ondataavailable event handler API handles dataavailable events, in response to run code Blob data is used to provide.

  • Dataavailable This event is triggered when MediaRecorder passes media data to your application for use. The data is provided in the Blob object that contains the data. This happens in four situations:

    • At the end of the media stream, all media data that has not been passed to the OnDataAvailable handler will be passed in a single Blob.

    • When MediaRecorder.stop() (en-us) is called, all media data captured since the start of recording or the last time a dataavailable event occurred is passed to the Blob; After that, the capture is over.

    • Call the MediaRecorder. RequestData () (en – US) dataavailable, passes since records began or event happened the last time to capture all the media data; The Blob then creates a new file and continues the media capture into the Blob.

    • If the timeslice property is passed to the MediaRecorder.start() (en-us) method that starts media capture, dataAvailable fires an event every timeslice millisecond. This means that each Blob has a specific duration (except for the last Blob, which may be shorter because it will be all that remains since the last event).

let mediaRecorder; const recordButton = document.querySelector('button#record'); RecordButton. AddEventListener (' click '() = > {the if (recordButton. TextContent = = =' start recording ') {startRecording (); } else { stopRecording(); Recordbutton. textContent = 'Start recording '; playButton.disabled = false; }}); function startRecording() { recordedBlobs = []; try { mediaRecorder = new MediaRecorder(window.stream); } catch (e) {console.error(' error while creating MediaRecorder :', e); } recordbutton. textContent = 'Stop recording '; playButton.disabled = true; mediaRecorder.ondataavailable = handleDataAvailable; mediaRecorder.start(); } function stopRecording() { mediaRecorder.stop(); } function handleDataAvailable(event) { if (event.data && event.data.size > 0) { recordedBlobs.push(event.data); }}Copy the code

Play a media stream

  • URL.createObjectURL()Static methods create oneDOMString, which contains a URL representing the object given in the parameter. The lifecycle of this URL and the window that created itdocumentBinding. This new URL object represents the specifiedFileObject orBlobObject.
let recordedBlobs;
const recordedVideo = document.querySelector('video#recorded');
const playButton = document.querySelector('button#play');

playButton.addEventListener('click', () => {
    const superBuffer = new Blob(recordedBlobs, { type: 'video/webm' });
    recordedVideo.src = null;
    recordedVideo.srcObject = null;
    recordedVideo.src = window.URL.createObjectURL(superBuffer);
    recordedVideo.controls = true;
    recordedVideo.play();
});
Copy the code

HTML

<link rel="stylesheet" href="./index.css"> <video id="gum" autoplay></video> <video id="recorded"></video> <div> <button Id ="start"> </button> <button ID ="record" disabled </button> </button ID ="play" disabled> play </button> </div> <script src="./index.js"></script>Copy the code

CSS

button {
    margin: 0 3px 10px 0;
    padding-left: 2px;
    padding-right: 2px;
    width: 99px;
}
  
button:last-of-type {
    margin: 0;
}
  
video {
    vertical-align: top;
    --width: 25vw;
    width: var(--width);
    height: calc(var(--width) * 0.5625);
}
  
video:last-of-type {
    margin: 0 0 20px 0;
}
  
video#gumVideo {
    margin: 0 20px 20px 0;
}
Copy the code

JavaScript

let mediaRecorder; let recordedBlobs; const recordedVideo = document.querySelector('video#recorded'); const recordButton = document.querySelector('button#record'); RecordButton. AddEventListener (' click '() = > {the if (recordButton. TextContent = = =' start recording ') {startRecording (); } else { stopRecording(); Recordbutton. textContent = 'Start recording '; playButton.disabled = false; }}); const playButton = document.querySelector('button#play'); playButton.addEventListener('click', () => { const superBuffer = new Blob(recordedBlobs, { type: 'video/webm' }); recordedVideo.src = null; recordedVideo.srcObject = null; recordedVideo.src = window.URL.createObjectURL(superBuffer); recordedVideo.controls = true; recordedVideo.play(); }); function handleDataAvailable(event) { if (event.data && event.data.size > 0) { recordedBlobs.push(event.data); } } function startRecording() { recordedBlobs = []; try { mediaRecorder = new MediaRecorder(window.stream); } catch (e) {console.error(' error while creating MediaRecorder :', e); } recordbutton. textContent = 'Stop recording '; playButton.disabled = true; mediaRecorder.ondataavailable = handleDataAvailable; mediaRecorder.start(); } function stopRecording() { mediaRecorder.stop(); } function handleSuccess(stream) { recordButton.disabled = false; window.stream = stream; const gumVideo = document.querySelector('video#gum'); gumVideo.srcObject = stream; } async function init(constraints) { try { const stream = await navigator.mediaDevices.getUserMedia(constraints); handleSuccess(stream); } catch (e) { console.error('navigator.getUserMedia error:', e); } } document.querySelector('button#start').addEventListener('click', async () => { document.querySelector('button#start').disabled = true; const constraints = { audio: {}, video: { width: 1280, height: 720 } }; await init(constraints); });Copy the code