Guide language: recently studied the principle and realization of web page recording audio and video, now on the current realization method to make a summary.

directory

  • The relevant API
  • Methods to introduce
  • We practice

The relevant API

Implementing this functionality involves two JS apis.

  • getUserMedia

  • MediaRecorder

Methods to introduce

getUserMedia

Get the device’s camera and microphone via the getUserMedia interface and return a Promise object.

Grammar var stream = the navigator. MediaDevices. GetUserMedia (constraints);

Constraints can be written in the following ways:

  • Request audio and Video
const constraints = {
    audio: true.video: true
}
Copy the code
  • Request a specific device video resolution
const constraints = {
    audio: true.video: {
        width: { 
            min: 1280 
        },
        height: { 
            min: 720}}}Copy the code
  • Use the front camera (default)
const constraints = {
    audio: true.video: {
        facingMode: "user"}}Copy the code
  • Mandatory use of rear camera
const constraints = {
    audio: true.video: {
        facingMode: {
            exact: "environment"}}}Copy the code

Such as:

const constraints = {
    audio: true.video: {
        width: 1280.height: 720}};async function createMedia() {
    try {
        let stream = await navigator.mediaDevices.getUserMedia(constraints);
        var video = document.querySelector('video');
        video.srcObject = stream;
        video.onloadedmetadata = function (e) {
            video.play();
        };
    } catch (error) {
        console.log(`getUserMedia: ${error}`);
    }
}

createMedia();
Copy the code

Of course, there are other methods you can use for this stream, such as

  • addTrackAdds a new track to the stream
  • getAudioTracksContains all the tracks in the stream
  • getVideoTracksEach video track contained in a media stream
  • getTracksAll objects in this stream

MediaRecorder

This is one way to record a stream.

  • startStart recording
  • stopThe end of the recording
  • onstopEnd of listening event
  • ondataavailableReal-time streaming data

Var mediaRecorder = new mediaRecorder (stream[, options]);

For example,

// stream is the audio and video stream obtained above
let options = {
    audioBitsPerSecond : 128000.videoBitsPerSecond : 2500000,}let mediaRecorder = new MediaRecorder(stream, options);

// Real time recording stream data
mediaRecorder.ondataavailable = function (e) {  
    console.log(e.data);
}

// Listener stops recording event and generates playback address
mediaRecorder.onstop = function () {
    let blob = new Blob(chunks, {'type': mediaRecorder.mimeType});
    let url = window.URL.createObjectURL(blob);
    console.log(url);
}
Copy the code

We practice

  • Page structure section
<audio controls src=""></audio>
<video controls src="" style="width: 100%;"></video>
<button id="start">Start the audio</button>
<button id="stop">The end of the audio</button>
<button id="play">Playback of audio</button>
<button id="startVideo">Start video</button>
<button id="stopVideo">The end of the video</button>
<button id="playVideo">Play the video</button>
Copy the code
  • Js part

Gets the element add event

// Get the button
let audioStart = document.querySelector('#start');
let audioStop = document.querySelector('#stop');
let audioPlay = document.querySelector('#play');
let startVideo = document.querySelector('#startVideo');
let stopVideo = document.querySelector('#stopVideo');
let playVideo = document.querySelector('#playVideo');

// Audio operation
audioStart.onclick = function () {  
    start('audio');
}

audioStop.onclick = function () {  
    stop('audio');
}

audioPlay.onclick = function () {  
    document.querySelector('audio').play();
}

// Video manipulation
startVideo.onclick = function () {  
    start('video');
}

stopVideo.onclick = function () {  
    stop('video');
}

playVideo.onclick = function () {  
    document.querySelector('video').play();
}
Copy the code

Start recording

// Start recording
function start (type) {
    let option = type == 'audio' ? {
        audio: true}, {video: true,
    }
    createMedia(type, option);
}
Copy the code

To stop recording

// Stop recording
function stop (type) {
    mediaRecorder.stop();
}

function stopSet (type) {  
    if (type == 'audio') {
        stream.getAudioTracks()[0].stop();
        stream = null;
    } else {
        stream.getVideoTracks()[0].stop();
    }
    stream = null;
    mediaRecorder = null;
    chunks = [];
    meida = null;
}
Copy the code

Common methods

// Global parameters
let stream = null,mediaRecorder = null,chunks = [], media = null;
async function createMedia (type, option) {  
    try {
        // Get the media stream
        stream = await navigator.mediaDevices.getUserMedia(option);
        media = document.querySelector(type);
        if (type === 'video') {
            media.srcObject = stream;
        }
        console.log(type, stream);

        / / to record flow
        let options = {
            audioBitsPerSecond : 128000.videoBitsPerSecond : 2500000,
        }
        mediaRecorder = new MediaRecorder(stream, options);
        console.log(type, mediaRecorder);

        mediaRecorder.ondataavailable = function (e) {  
            chunks.push(e.data);
        }

        mediaRecorder.start();

        // Stop recording
        mediaRecorder.onstop = function () {
            let blob = new Blob(chunks, {'type': mediaRecorder.mimeType});
            let url = window.URL.createObjectURL(blob);
            if (type === 'video') {
                media.srcObject = null; } media.src = url; stopSet(type); }}catch (error) {
        console.log('getUserMedia:', error); }}Copy the code

Look at the effect

If you want to experience it, you can open this audio and video recording, preferably on your phone.

Ok, that’s all for today’s tutorial, bye!