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)
傳回 Promise<DesktopCapturerSource[]>
- 解析為 DesktopCapturerSource 物件的陣列,每個 DesktopCapturerSource
代表一個可以擷取的螢幕或個別視窗。
注意 在 macOS 10.15 Catalina 或更高版本上擷取螢幕內容需要使用者同意,這可以使用 systemPreferences.getMediaAccessStatus
偵測。
注意事項
由於基本限制,navigator.mediaDevices.getUserMedia
在 macOS 上無法用於音訊擷取,因為想要存取系統音訊的應用程式需要已簽署的 Kernel 擴充功能。Chromium,以及延伸的 Electron,並未提供此功能。
可以透過使用另一個 macOS 應用程式 (例如 Soundflower) 擷取系統音訊,並將其傳遞到虛擬音訊輸入裝置來規避此限制。然後可以使用 navigator.mediaDevices.getUserMedia
查詢此虛擬裝置。