desktopCapturer

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

进程: Renderer

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

  1. // In the renderer process.
  2. const {desktopCapturer} = require('electron')
  3. desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
  4. if (error) throw error
  5. for (let i = 0; i < sources.length; ++i) {
  6. if (sources[i].name === 'Electron') {
  7. navigator.mediaDevices.getUserMedia({
  8. audio: false,
  9. video: {
  10. mandatory: {
  11. chromeMediaSource: 'desktop',
  12. chromeMediaSourceId: sources[i].id,
  13. minWidth: 1280,
  14. maxWidth: 1280,
  15. minHeight: 720,
  16. maxHeight: 720
  17. }
  18. }
  19. })
  20. .then((stream) => handleStream(stream))
  21. .catch((e) => handleError(e))
  22. return
  23. }
  24. }
  25. })
  26. function handleStream (stream) {
  27. const video = document.querySelector('video')
  28. video.srcObject = stream
  29. video.onloadedmetadata = (e) => video.play()
  30. }
  31. function handleError (e) {
  32. console.log(e)
  33. }

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

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

  1. const constraints = {
  2. audio: {
  3. mandatory: {
  4. chromeMediaSource: 'desktop'
  5. }
  6. },
  7. video: {
  8. mandatory: {
  9. chromeMediaSource: 'desktop'
  10. }
  11. }
  12. }

方法

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.

Note Capturing the screen contents requires user consent on macOS 10.15 Catalina or higher, which can detected by [systemPreferences.getMediaAccessStatus].

注意事项

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

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