メインコンテンツへ飛ぶ

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' })
},
() => {
// Deny the request if no sources could be retrieved, for example
// when the user cancels the PipeWire picker on Linux.
callback(null)
}
)
// If true, use the system picker if available.
// 注: 現在これは実験的なものです。 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)​

History
  • options Object
    • types string[] - キャプチャされるデスクトップソースの種別を列挙した文字列の配列。指定できる種別は、screen と window です。
    • thumbnailSize Size (任意) - メディアソースのサムネイルをスケーリングするサイズ。省略値は 150 x 150 です。サムネイルが不要な場合は、幅または高さを 0 に設定してください。これにより、各ウィンドウおよび画面のコンテンツをキャプチャするために必要な処理時間が節約されます。
    • fetchWindowIcons boolean (任意) - ウインドウアイコンの取得を有効にするには true に設定します。デフォルト値は false です。 false の場合、ソースの appIcon プロパティは null を返します。ソースが screen 型の場合も同様です。

戻り値 Promise<DesktopCapturerSource[]> - DesktopCapturerSource オブジェクトの配列で解決します。各 DesktopCapturerSource は、キャプチャできる画面または個々のウィンドウを表します。

注釈
  • macOS 14.2 以降では、音声のキャプチャに NSAudioCaptureUsageDescription の Info.plist キーが必要になります – 詳細。 * macOS 10.15 以降では、画面のコンテンツをキャプチャするにはユーザーの同意が必須となります。これは、systemPreferences.getMediaAccessStatus で検出できます。

Caveats​

Linux​

Linux では、Pipewire を使用する場合 desktopCapturer.getSources(options) は単一のソースのみを返します。

PipeWire は、スクリーンとウインドウの両方に対して一つのキャプチャをサポートしています。ウインドウとスクリーンのタイプを要求すると、選択したソースがウインドウキャプチャとして返されます。

macOS v14.2 以降​

desktopCapturer が音声をキャプチャするためには、NSAudioCaptureUsageDescription の Info.plist キーが必要になります。一方、ターミナルや IDE などの別のプログラムから Electron を実行している場合は、 その親プログラムに Info.plist キーが含まれている必要があります。

This is in order to facilitate use of Apple's CoreAudio Tap API by Chromium, which is gated behind the "System Audio Recording" privacy permission. macOS attributes that permission to the responsible process, so when running unpackaged from a terminal or IDE it is the terminal or IDE that must be granted access.

[!WARNING] If the permission is missing or has been denied, desktopCapturer still produces an audio track, but it is created in the ended state and never delivers samples. No warning or error is surfaced to JavaScript.

Since Electron 39, Chromium uses the CoreAudio Tap API by default for system audio capture on macOS 14.2 and later. There is no automatic fallback to the older ScreenCaptureKit-based "Screen & System Audio Recording" path if tap creation fails, and as of Electron 45 the MacCatapLoopbackAudioForScreenShare feature flag that previously allowed opting back into it has been removed upstream and no longer has any effect.

macOS v12.7.6 以前​

システムのオーディオにアクセスしようとするアプリには、 署名付きカーネル拡張が必要となるという根本的な制約があります。これにより、macOS v12.7.6 またはそれ以前では、音声キャプチャのために navigator.mediaDevices.getUserMedia は動作しません。 Chrome、ひいては Electron はこれを提供していません。 macOS 13 以降でのみ、Apple は、署名付きカーネル拡張機能を必要とせずにデスクトップオーディオをキャプチャする API を提供します。

この制限を回避するには、 BlackHole や Soundflower といった別の macOS アプリでシステムオーディオをキャプチャし、 仮想オーディオ入力デバイス経由で出力するように設定します。この仮想デバイスは、 navigator.mediaDevices.getUserMedia を使用して照会できます。