跳至主要內容

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 物件
    • types 字串陣列 - 列出要擷取的桌面來源類型的字串陣列,可用的類型可以是 screenwindow
    • thumbnailSize Size (選用) - 媒體來源縮圖應縮放到的尺寸。預設值為 150 x 150。如果您不需要縮圖,請將寬度或高度設定為 0。這將節省擷取每個視窗和螢幕內容所需的處理時間。
    • fetchWindowIcons 布林值 (選用) - 設定為 true 以啟用擷取視窗圖示。預設值為 false。當為 false 時,來源的 appIcon 屬性會傳回 null。如果來源的類型為螢幕,也會發生相同的情況。

傳回 Promise<DesktopCapturerSource[]> - 解析為 DesktopCapturerSource 物件的陣列,每個 DesktopCapturerSource 代表一個可以擷取的螢幕或個別視窗。

注意 在 macOS 10.15 Catalina 或更高版本上擷取螢幕內容需要使用者同意,這可以使用 systemPreferences.getMediaAccessStatus 偵測。

注意事項

由於基本限制,navigator.mediaDevices.getUserMedia 在 macOS 上無法用於音訊擷取,因為想要存取系統音訊的應用程式需要已簽署的 Kernel 擴充功能。Chromium,以及延伸的 Electron,並未提供此功能。

可以透過使用另一個 macOS 應用程式 (例如 Soundflower) 擷取系統音訊,並將其傳遞到虛擬音訊輸入裝置來規避此限制。然後可以使用 navigator.mediaDevices.getUserMedia 查詢此虛擬裝置。