メインコンテンツへ飛ぶ

desktopCapturer

navigator.mediaDevices.getUserMedia APIを使用して、デスクトップからの音声と映像のキャプチャに利用できるメディアソース関連の情報にアクセスします。

プロセス: Main

以下の例では、タイトルが 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' })
})
})

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>

See navigator.mediaDevices.getDisplayMedia for more information.

Note: navigator.mediaDevices.getDisplayMedia does not permit the use of deviceId for selection of a source - see specification.

メソッド

desktopCapturer モジュールには以下のメソッドがあります。

desktopCapturer.getSources(options)

  • options Object
    • 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で検知できます。

Caveats

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

Soundflower のような他の macOS アプリでシステムオーディオをキャプチャし、それを仮想オーディオ入力デバイスに渡すことでこの制限を回避することが可能です。 この仮想デバイスは、 navigator.mediaDevices.getUserMedia.を使用して照会できます。