跳转到主要内容

desktopCapturer

使用 navigator.mediaDevices.getUserMedia API 访问可用于捕获桌面音频和视频的媒体源信息。

进程:主进程

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

// main.js
const { app, BrowserWindow, desktopCapturer, session } = require('electron')

app.whenReady().then(() => {
const mainWindow = new BrowserWindow()

session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
desktopCapturer.getSources({ types: ['screen'] }).then((sources) => {
// Grant access to the first screen found.
callback({ video: sources[0], audio: 'loopback' })
})
// If true, use the system picker if available.
// Note: this is currently experimental. If the system picker
// is available, it will be used and the media request handler
// will not be invoked.
}, { useSystemPicker: true })

mainWindow.loadFile('index.html')
})
// renderer.js
const startButton = document.getElementById('startButton')
const stopButton = document.getElementById('stopButton')
const video = document.querySelector('video')

startButton.addEventListener('click', () => {
navigator.mediaDevices.getDisplayMedia({
audio: true,
video: {
width: 320,
height: 240,
frameRate: 30
}
}).then(stream => {
video.srcObject = stream
video.onloadedmetadata = (e) => video.play()
}).catch(e => console.log(e))
})

stopButton.addEventListener('click', () => {
video.pause()
})
<!-- index.html -->
<html>
<meta http-equiv="content-security-policy" content="script-src 'self' 'unsafe-inline'" />
<body>
<button id="startButton" class="button">Start</button>
<button id="stopButton" class="button">Stop</button>
<video width="320" height="240" autoplay></video>
<script src="renderer.js"></script>
</body>
</html>

有关更多信息,请参阅 navigator.mediaDevices.getDisplayMedia

注意

navigator.mediaDevices.getDisplayMedia 不允许使用 deviceId 来选择源 - 请参阅 规范

方法

desktopCapturer 模块具有以下方法:

desktopCapturer.getSources(options)

  • options Object
    • types string[] - 一个字符串数组,列出了要捕获的桌面源的类型,可用类型为 screenwindow
    • thumbnailSize Size (可选) - 媒体源缩略图应缩放到的尺寸。默认为 150 x 150。如果您不需要缩略图,请将宽度或高度设置为 0。这将节省捕获每个窗口和屏幕内容所需的处理时间。
    • fetchWindowIcons boolean (可选) - 设置为 true 以启用获取窗口图标。默认值为 false。如果为 false,则源的 appIcon 属性返回 null。如果源的类型为 screen,情况也相同。

返回 Promise<DesktopCapturerSource[]> - 解析为 DesktopCapturerSource 对象数组,每个 DesktopCapturerSource 代表一个可以捕获的屏幕或单个窗口。

注意

在 macOS 10.15 Catalina 或更高版本上,捕获屏幕内容需要用户同意,这可以通过 systemPreferences.getMediaAccessStatus 检测。

注意事项

在使用 Pipewire 时,desktopCapturer.getSources(options) 在 Linux 上仅返回单个源。

PipeWire 支持对屏幕和窗口的单个捕获。如果您请求窗口和屏幕类型,则返回的选定源将是窗口捕获。

由于一个基本限制,即想要访问系统音频的应用程序需要 签名内核扩展navigator.mediaDevices.getUserMedia 在 macOS 上无法用于音频捕获。Chromium,以及 Electron,都不提供此功能。

可以通过使用 Soundflower 等其他 macOS 应用程序捕获系统音频,并通过虚拟音频输入设备进行传递来绕过此限制。然后可以使用 navigator.mediaDevices.getUserMedia 查询此虚拟设备。