網頁錄像錄音功能的實現之MediaRecorder的使用


前面介紹了通過H5實現在網頁內打開攝像頭和麥克風,實現截圖和圖像預覽的相關知識。

getUserMedia API及HTML5 調用攝像頭和麥克風

一個簡單的demo  實現攝像頭的調用及視頻錄制,截圖,下載等功能,逐漸完善中。。。。

地址:https://github.com/zhangdexian/videorecorder

頁面效果:

 

但是我們無法將將數據保存到本地甚至上傳到我們自己的服務器,本篇主要是針對錄像錄音的保存做一個簡單的介紹和學習。

 

首先來看一下官方的文檔介紹:

構造器 ConstructorSection

MediaRecorder()
Creates a new MediaRecorder object, given a MediaStream to record. Options are available to do things like set the container's MIME type (such as "video/webm" or "video/mp4") and the bit rates of the audio and video tracks or a single overall bit rate.

構造器接受一個MediaStream流對象,可以看到還可以配置MIME type類型及比特率。

屬性 PropertiesSection


MediaRecorder.mimeType Read only // 返回
MediaRecorder實例的mimetype類型 只讀
 Returns the MIME type that was selected as the recording container for the MediaRecorder object when it was created.
MediaRecorder.state Read only // 返回
MediaRecorder當前狀態:閑置、錄制中和暫停 只讀
 Returns the current state of the MediaRecorder object (inactive, recording, or paused.)
MediaRecorder.stream Read only // 返回所錄制的流對象 只讀 Returns the stream that was passed into the constructor when the MediaRecorder was created.
MediaRecorder.ignoreMutedMedia // 當媒體流靜音時是否忽略 Indicates whether the MediaRecorder instance will record input when the input MediaStreamTrack is muted. If this attribute is false, MediaRecorder will record silence for audio and black frames for video. The default is false.
MediaRecorder.videoBitsPerSecond Read only
// 返回視頻的比特率 只讀 Returns the video encoding bit rate in use. This may differ from the bit rate specified in the constructor (if it was provided).
MediaRecorder.audioBitsPerSecond Read only
// 返回音頻的比特率 只讀
 Returns the audio encoding bit rate in use. This may differ from the bit rate specified in the constructor (if it was provided).

方法 MethodsSection

MediaRecorder.isTypeSupported()     //  返回給定的MIME type是否被當前客戶端支持
 Returns a Boolean value indicating if the given MIME type is supported by the current user agent .
MediaRecorder.pause() // 暫定錄制 Pauses the recording of media.
MediaRecorder.requestData() // 返回錄制的二進制數據,調用這個方法后會生成一個新的Blob對象 Requests a Blob containing the saved data received thus far (or since the last time requestData() was called. After calling this method, recording continues, but in a new Blob.
MediaRecorder.resume() // 恢復錄制 Resumes recording of media after having been paused.
MediaRecorder.start() // 開始錄制 Begins recording media; this method can optionally be passed a timeslice argument with a value in milliseconds. If this is specified, the media will be captured in separate chunks of that duration, rather than the default behavior of recording the media in a single large chunk.
MediaRecorder.stop() // 停止錄制 Stops recording, at which point a dataavailable event containing the final Blob of saved data is fired. No more recording occurs.

事件 Event HandlersSection

MediaRecorder.ondataavailable   // 有可用數據流時觸發,e.data即時需要的視頻數據
Called to handle the dataavailable event, which is periodically triggered each time timeslice milliseconds of media have been recorded (or when the entire media has been recorded, if timeslice wasn't specified). The event, of type BlobEvent, contains the recorded media in its data property. You can then collect and act upon that recorded media data using this event handler.
MediaRecorder.onerror An EventHandler called to handle the error event, including reporting errors that arise with media recording. These are fatal errors that stop recording. The received event is based on the MediaRecorderErrorEvent interface, whose error property contains a DOMException that describes the actual error that occurred.
MediaRecorder.onpause An EventHandler called to handle the pause event, which occurs when media recording is paused.
MediaRecorder.onresume An EventHandler called to handle the resume event, which occurs when media recording resumes after being paused.
MediaRecorder.onstart An EventHandler called to handle the start event, which occurs when media recording starts.
MediaRecorder.onstop An EventHandler called to handle the stop event, which occurs when media recording ends, either when the MediaStream ends — or after the MediaRecorder.stop() method is called.

下面是一個簡單的例子:

if (navigator.mediaDevices) {
  console.log('getUserMedia supported.');

  var constraints = { audio: true };
  var chunks = [];

  navigator.mediaDevices.getUserMedia(constraints)
  .then(function(stream) {

    var mediaRecorder = new MediaRecorder(stream);

    visualize(stream);

    record.onclick = function() {
      mediaRecorder.start();
      console.log(mediaRecorder.state);
      console.log("recorder started");
      record.style.background = "red";
      record.style.color = "black";
    }

    stop.onclick = function() {
      mediaRecorder.stop();
      console.log(mediaRecorder.state);
      console.log("recorder stopped");
      record.style.background = "";
      record.style.color = "";
    }

    mediaRecorder.onstop = function(e) {
      console.log("data available after MediaRecorder.stop() called.");

      var clipName = prompt('Enter a name for your sound clip');

      var clipContainer = document.createElement('article');
      var clipLabel = document.createElement('p');
      var audio = document.createElement('audio');
      var deleteButton = document.createElement('button');
     
      clipContainer.classList.add('clip');
      audio.setAttribute('controls', '');
      deleteButton.innerHTML = "Delete";
      clipLabel.innerHTML = clipName;

      clipContainer.appendChild(audio);
      clipContainer.appendChild(clipLabel);
      clipContainer.appendChild(deleteButton);
      soundClips.appendChild(clipContainer);

      audio.controls = true;
      var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' });
      chunks = [];
      var audioURL = URL.createObjectURL(blob);
      audio.src = audioURL;
      console.log("recorder stopped");

      deleteButton.onclick = function(e) {
        evtTgt = e.target;
        evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode);
      }
    }

    mediaRecorder.ondataavailable = function(e) {
      chunks.push(e.data);
    }
  })
  .catch(function(err) {
    console.log('The following error occurred: ' + err);
  })
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM