Skip to content

Latest commit

 

History

History
84 lines (66 loc) · 3.36 KB

desktop-capturer.md

File metadata and controls

84 lines (66 loc) · 3.36 KB

desktopCapturer

通过[navigator.mediaDevices.getUserMedia] API ,可以访问那些用于从桌面上捕获音频和视频的媒体源信息。

进程: Renderer

下面的示例演示如何从标题为 Electron 的桌面窗口捕获视频:

// In the renderer process.
const {desktopCapturer} = require('electron')

desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
  if (error) throw error
  for (let i = 0; i < sources.length; ++i) {
    if (sources[i].name === 'Electron') {
      navigator.mediaDevices.getUserMedia({
        audio: false,
        video: {
          mandatory: {
            chromeMediaSource: 'desktop',
            chromeMediaSourceId: sources[i].id,
            minWidth: 1280,
            maxWidth: 1280,
            minHeight: 720,
            maxHeight: 720
          }
        }
      })
      .then((stream) => handleStream(stream))
      .catch((e) => handleError(e))
      return
    }
  }
})

function handleStream (stream) {
  const video = document.querySelector('video')
  video.srcObject = stream
  video.onloadedmetadata = (e) => video.play()
}

function handleError (e) {
  console.log(e)
}

若要从 desktopCapturer 提供的源捕获视频, 则传递给 [navigator.mediaDevices.getUserMedia] 的约束必须包括 chromeMediaSource: "desktop"audio: false

要从整个桌面同时捕获音频和视频, 传递给 [navigator.mediaDevices.getUserMedia] 的约束必须包括 chromeMediaSource: ' desktop ', 同时用于 audiovideo, 但不应包括 chromeMediaSourceId 约束。

const constraints = {
  audio: {
    mandatory: {
      chromeMediaSource: 'desktop'
    }
  },
  video: {
    mandatory: {
      chromeMediaSource: 'desktop'
    }
  }
}

方法

desktopCapturer 模块有以下方法:

desktopCapturer.getSources(options)

  • options 对象
    • 类型String[]-列出要捕获的桌面源类型的字符串数组, 可用类型为 screenwindow
    • thumbnailSizeSize(可选) - 媒体源缩略图应缩放到的尺寸大小。 默认是 150 x 150。 当您不需要缩略图时,设置宽度或高度为0。 这将节省用于获取每个窗口和屏幕内容时的处理时间。
    • fetchWindowIcons Boolean (可选) - 设置为true以便启用获取窗口图标。 默认值为false。 当值为false时,源的appIcon属性返回null。 Same if a source has the type screen.

Returns Promise<DesktopCapturerSource[]> - Resolves with an array of DesktopCapturerSource objects, each DesktopCapturerSource represents a screen or an individual window that can be captured.

注意事项

由于存在基本限制,因此navigator.mediaDevices.getUserMedia 无法在macOS上进行音频捕获,因此要访问系统音频的应用程序需要一个签名内核拓展. Chromium, and by extension Electron, does not provide this.

通过使用另一个MacOS应用程序(如Soundflower)捕获系统音频并将其通过虚拟音频输入设备来规避此限制是可能的。 然后可以用 navigator.mediaDevices.getUserMedia查询该虚拟设备。