跳转到主要内容

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 时,sources 的 appIcon 属性返回 null。如果源类型为 screen,则情况相同。

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

注意

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

注意事项

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

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