- Electron 教程
- Electron - 首頁
- Electron - 概述
- Electron - 安裝
- Electron 如何工作?
- Electron - Hello World
- Electron - 構建 UI
- Electron - 檔案處理
- Electron - 原生 Node 庫
- 程序間通訊 (IPC)
- Electron - 系統對話方塊
- Electron - 選單
- Electron - 系統托盤
- Electron - 通知
- Electron - Webview
- Electron - 音訊和影片捕獲
- Electron - 定義快捷鍵
- Electron - 環境變數
- Electron - 除錯
- Electron - 打包應用程式
- Electron - 資源
- Electron 有用資源
- Electron - 快速指南
- Electron - 有用資源
- Electron - 討論
Electron - 音訊和影片捕獲
如果您正在構建用於螢幕共享、語音備忘錄等應用程式,則音訊和影片捕獲是重要的特性。如果您需要應用程式捕獲個人資料圖片,它們也很有用。
我們將使用 getUserMedia HTML5 API 來捕獲 Electron 的音訊和影片流。讓我們首先在 main.js 檔案中設定我們的主程序,如下所示:
const {app, BrowserWindow} = require('electron')
const url = require('url')
const path = require('path')
let win
// Set the path where recordings will be saved
app.setPath("userData", __dirname + "/saved_recordings")
function createWindow() {
win = new BrowserWindow({width: 800, height: 600})
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
}
app.on('ready', createWindow)
現在我們已經設定了主程序,讓我們建立將捕獲此內容的 HTML 檔案。建立一個名為 index.html 的檔案,內容如下:
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>Audio and Video</title>
</head>
<body>
<video autoplay></video>
<script type = "text/javascript">
function errorCallback(e) {
console.log('Error', e)
}
navigator.getUserMedia({video: true, audio: true}, (localMediaStream) => {
var video = document.querySelector('video')
video.src = window.URL.createObjectURL(localMediaStream)
video.onloadedmetadata = (e) => {
// Ready to go. Do some stuff.
};
}, errorCallback)
</script>
</body>
</html>
上述程式將生成以下輸出:
您現在擁有來自網路攝像頭和麥克風的流。您可以透過網路傳送此流,或將其儲存為您喜歡的格式。
檢視 MDN 文件 以瞭解如何捕獲影像以獲取網路攝像頭中的影像並將其儲存。這是使用 HTML5 getUserMedia API 完成的。您還可以使用 Electron 自帶的 desktopCapturer 模組捕獲使用者桌面。現在讓我們看看如何獲取螢幕流的示例。
使用與上面相同的 main.js 檔案,並編輯 index.html 檔案以包含以下內容:
desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
if (error) throw error
for (let i = 0; i < sources.length; ++i) {
if (sources[i].name === 'Your Window Name here!') {
navigator.webkitGetUserMedia({
audio: false,
video: {
mandatory: {
chromeMediaSource: 'desktop',
chromeMediaSourceId: sources[i].id,
minWidth: 1280,
maxWidth: 1280,
minHeight: 720,
maxHeight: 720
}
}
}, handleStream, handleError)
return
}
}
})
function handleStream (stream) {
document.querySelector('video').src = URL.createObjectURL(stream)
}
function handleError (e) {
console.log(e)
}
我們使用了 desktopCapturer 模組來獲取有關每個開啟視窗的資訊。現在,您可以根據傳遞給上述 if 語句 的名稱來捕獲特定應用程式或整個螢幕的事件。這將僅將該螢幕上發生的情況流式傳輸到您的應用程式。
您可以參考 此 StackOverflow 問題 以詳細瞭解用法。
廣告