メインコンテンツへスキップ

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 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で検出できます。

注意点

navigator.mediaDevices.getUserMedia は、システムオーディオにアクセスしたいアプリには署名付きカーネル拡張機能が必要になるという根本的な制限により、macOSではオーディオキャプチャで機能しません。Chromium、ひいてはElectronはこれを提供していません。

この制限は、Soundflowerのような別のmacOSアプリでシステムオーディオをキャプチャし、仮想オーディオ入力デバイスを介して渡すことで回避できます。この仮想デバイスは、navigator.mediaDevices.getUserMediaでクエリできます。