网页录像录音功能的实现之MediaRecorder的使用

前面介绍了通过H5实现在网页内打开摄像头和麦克风,实现截图和图像预览的相关知识。

getUserMedia API及HTML5 调用摄像头和麦克风

但是我们无法将将数据保存到本地甚至上传到我们自己的服务器,本篇主要是针对录像录音的保存做一个简单的介绍和学习。

首先来看一下官方的文档介绍:

构造器 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);
  })
}

原文地址:https://www.cnblogs.com/cangqinglang/p/10218505.html

时间: 2024-10-10 07:14:03

网页录像录音功能的实现之MediaRecorder的使用的相关文章

delphi android 录像(使用了JMediaRecorder,MediaRecorder的使用方法)

delphi xe系列自带的控件都无法保存录像,经网友帮忙,昨天终于实现了录像功能(但有个问题是录像时无画面显示),程序主要使用了JMediaRecorder,MediaRecorder的使用方法可参考网上java的相关说明,下面代码是可以正常录像的: unit Unit8; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, Androidapi.Helpe

Android Camera开发讲解

概述 Android手机关于Camera的使用,一是拍照,二是摄像,由于Android提供了强大的组件功能,为此对于在Android手机系统上进行Camera的开发,我们可以使用两类方法:一是借助Intent和MediaStore调用系统Camera App程序来实现拍照和摄像功能,二是根据Camera API自写Camera程序. 基础知识 Android系统提供API来支持自定义相机拍照和系统拍照,以下是有关的类: Camera 该类提供基础API来使用设备上的相机,且该类可以为你的应用提供

Android Camera开发之基础知识篇

概述 Android框架支持设备的相机拍照和录像功能,你的应用可以直接调用系统的Camera应用来拍照或者录像(比如微信拍照),当然也可以利用Android系统提供的API开发一个Camera应用来实现相机拍照和录像功能(比如市面上流行的360相机).此篇文章主要记录相机开发有关的基础知识,以及带着自己的理解翻译Camera官方文档,如有翻译不恰当支出,还请指出改正.当然我会开一个有关相机开发的一个系列,该系列主要内容包括如下: 相机基本预览拍照功能. 实现相机的Flash,Hdr,滤镜,前后摄

MediaRecorder录像怎么旋转呀?

============问题描述============ 最近做的项目摄像头是跟手机按90度安装的,用MediaRecorder录像还是按摄像头的方向而不是手机的方向,录出来的是90度旋转的,试了很多方法都不管用.MediaRecorder.setOrientationHint没有效果,在底层AuthorDriver那都没有对其实现:Camera.Parameters.setRotation然后再Camera.setParameters和MediaRecorder.setCamera也没有效果,

MediaRecorder录像那些事

最近在做一个项目需要运用到MediaRecorder的API,之前都没接触过这部分,开始着手弄的时候各种各样的问题,真是让人崩溃呀! 最后通过网上的资料和大神的指点,当然也有自己几天坚持不懈的努力,终于搞定了! 录像之前我采用Camera进行预览Camera.startPreview();预览的时候不知道为什么非常模糊,完全看不清,后来给Camera设置一些参数就清晰了,代码如下: 1 mParams = mCamera.getParameters(); 2 mParams.setPicture

Android调用手机摄像头使用MediaRecorder录像并播放

最近在项目开发中需要调用系统的摄像头录像并播放. 在开发中遇到了两个问题,记录下: (1)开发过程中出现摄像头占用,启动失败,报错.但是我已经在onDestory()中关闭了资源. 报错原因:打开程序,调用摄像头,按Home键再打开程序调用,报错摄像头被占用. 解决:在onStop()中关闭资源,在onResume()中判断是否为null,否则实例化资源. (2)其中我录像播放的代码写在Fragment+ViewPager中,在来回切换Fragment的时候,摄像头只能调用一次,并且所在的Fra

PhoneGap录像 以及 录音功能 简单代码实现

1,录音功能 navigator.device.capture.captureAudio( function(files){//成功回调函数 Ext.getCmp("video_files_mainview").config.param.sourceobj.startUpload(files[0].fullPath, 2); }, function(error){//失败回调函数 // navigator.notification.alert('Error code: ' + erro

Android 中使用MediaRecorder进行录像详解(视频录制)

在这里给出自己的一个测试DEMO,里面注释很详细.简单的视频录制功能. package com.video; import java.io.IOException; import android.app.Activity; import android.content.pm.ActivityInfo; import android.graphics.PixelFormat; import android.media.MediaRecorder; import android.os.Bundle;

Android MediaRecorder实现暂停断点录音功能

基本原理如下:MediaRecorder通过MIC录音,系统没有自带的pause功能,每次暂停录音,都会结束本次的录音.现在本人的设计思路是:MediaRecorder录音暂停时,保存这段所录下的音频A,继续录音后,再次暂停,保留录音音频B:以此类推直到最终的录音结束时,依次读取之前保存的A.B……的录音文件,并将其合并在一起.涉及的技术:文件的保存读取.音频的合并等 音频的合并:设置MediaRecorder的音频输出格式mMediaRecorder01.setOutputFormat(Med