javascript-将getusermedia数据附加到mediasource

我对mediastream和mediasource api的经验有限,您认为从getusermedia获取数据并将该数据附加到mediasource的最佳方法是什么?现在,我正在使用MediaRecorder记录数据,然后将其附加到新的mediasource对象上.但这只会返回空白视频.这是我目前正在做的事情.

function createElem (tagName) {
  var elem = document.createElement(tagName)
  elem.controls = true
  elem.autoplay = true 
  elem.play() 
  document.body.appendChild(elem)
  return elem
}

navigator.getUserMedia({ video: true, audio: false }, function (stream) {
  var recorder = new MediaRecorder(stream)
  var wrapper = new MediaSource()

  var elem = createElem('video')
  elem.src = window.URL.createObjectURL(wrapper)
  wrapper.addEventListener('sourceopen', sourceOpen)

  function sourceOpen () {
    var source = wrapper.addSourceBuffer('video/webm;codecs=vp9')
    recorder.ondataavailable = function (e) {
      source.appendBuffer(new Uint8Array(e.data))
    }
  }
  recorder.start(1000)
}, function () {})

我知道您可以只使用video.src = window.URL.createObjectURL(stream),但我想处理原始数据.有可能这样做吗?这是一个小提琴,所以您可以玩it.

解决方法:

我遇到了类似的问题,而this answer为我工作.
我猜问题是MediaRecorder API返回Blob,但是需要ArrayBuffer.根据the MDN documentation:“从Blob读取内容的唯一方法是使用FileReader”.

我改编了您的fiddle,但仅在Chrome 53中对其进行了测试.

navigator.getUserMedia({ video: true, audio: false }, successCallback, function (err) { console.error('Error:', err, err.stack); })

function successCallback(stream) {
    var recorder, source = new MediaSource()

    var elem = createVideoElem()
    elem.src = URL.createObjectURL(source)  
    source.addEventListener('sourceopen', sourceOpen)

    function sourceOpen () {
        var buffer = source.addSourceBuffer('video/webm;codecs=vp9')
        recorder = new MediaRecorder(stream)
        recorder.start(1000)

        recorder.ondataavailable = function (e) {
            var fileReader = new FileReader();
            fileReader.onload = function() {
                buffer.appendBuffer(fileReader.result);
            };
            fileReader.readAsArrayBuffer(e.data);
        }
    }
}

function createVideoElem () {
    var elem = document.createElement('video')
    elem.controls = true
    elem.autoplay = true // for chrome
    elem.play() // for firefox
    document.body.appendChild(elem)
    return elem
}
上一篇:H5通过navigator.mediaDevices.getUserMedia调用手机摄像头


下一篇:webRTC实战总结