作者簡介:張乾澤,聲網 Agora Web 研發工程師
對於在線教育、醫療、視頻會議等場景來講,開發面向 Windows、Mac 的跨平臺客戶端是必不可少的一步。在過去,每個操作系統的應用需用特定的編程語言編寫,每個客戶端都需要單獨開發。而現在我們可以利用多種工具、框架進行跨平臺開發。Electron 就是其中最熱門的一個。
Electron 的前身是Atom Shell,是基於Node.js 和 Chromium 開源項目。它讓前端開發者也可以使用 JavaScript,HTML 和 CSS 構建跨平臺的桌面應用程序。
Electron 兼容 Mac、Windows 和 Linux。利用它構建的應用可在這三個操作系統上面運行。我們在很多著名項目中都能看到它的身影,比如 Slack、Cocos Creator、Visual Studio Code 等 500 多個項目。
本文將爲大家分析利用 Electron 做視頻會議應用的幾種實現思路及其優缺點,同時結合 demo 實例,分享如何基於 Electron 與聲網 Agora Web SDK 開發一個視頻會議應用。
實現視頻會議的思路
如何利用 Electron 實現一個視頻會議應用?這主要取決於使用什麼技術來實現作爲業務核心的 RTC 部分。
我們使用 C++ SDK 就可以實現。我們可以通過 NodeJS 插件 node-gyp 將 C++ 的庫編譯成 NodeJS 可以直接使用的文件,界面部分則通過 Web 來實現,最後 RTC 業務部分則使用編譯的插件直接調用 C++ 接口。
這種方式的優點是直接調用 C++ 接口,在性能和穩定性上有一定優勢。但是,缺點是 Native 模塊與 Web 模塊的交互會相對複雜。
儘管 NodeJS 可以直接調用 C++ 的接口,但若 C++ 要通過回調向 Node 部分傳遞數據,則需要確保數據傳輸到 Electron 所在的線程上, Electron 纔可以收到回調。又比如,若 C++ SDK 使用了具有平臺差異的動態庫依賴,則在使用 node-gyp 編譯的過程中必須在不同平臺上編譯不同的版本纔可以在 Electron 中正常使用。
基於 Agora Web SDK 實現音視頻通話
我們需要在 Electron 環境中創建一個名爲 web-app 的目錄,在裏面創建基本的 Web 部分內容並快速實現一個視頻通話通能。
創建 AgoraRTC 實例並加入頻道:
1let client = AgoraRTC.CreateClient({mode:"interop"})
初始化 appid 並加入頻道:
1 client.init(options.key, () => {
2 console.log("AgoraRTC client initialized")
3 client.join(options.key, options.channel, options.uid, (uid) => {
4 console.log("User " + uid + " join channel successfully")
5 console.log(new Date().toLocaleTimeString())
6 // create localstream
7 resolve(uid)
8 })
9 })
創建本地流並推送:
1let stream = AgoraRTC.creatStream(merge(defaultConfig.config))
2localStream.init(() =>{
3 client.publish(localStream, err => {
4 console.log("Publish local stream error: " + err);
5 localStream.play("element_id")
6 })
7},
在完成上面的步驟後,你應該就能看到自己的視頻畫面了,下一步我們要讓這部分代碼在 Electron 的 App 容器中跑起來。
創建 BrowserWindow 實例並讀取 web-app 目錄中的內容:
1const electron = require('electron')
2// Module to control application life.
3const app = electron.app
4// Module to create native browser window.
5const BrowserWindow = electron.BrowserWindow
6let mainwindow
7function createWindow () {
8 // Create the browser window.
9mainWindow = new BrowserWindow({width: 800, height: 600})
10 // and load the index.html of the app.
11 mainWindow.loadURL(url.format({
12 pathname: path.join(__dirname, './web-app/dist/index.html'),
13 protocol: 'file:',
14 slashes: true
15 }))
16mainWindow.webContents.openDevTools()
17//Open the DevTools
18//mainWindow.webContents.openDevTools()
19//Emitted when the window is closed.
20mainWindow.on('closed',function(){
21 // Dereference the window object, usually you would store windows
22 // in an array if your app supports multi windows, this is the time
23 // when you should delete the corresponding element.
24 mainWindow = null
25})
完成後使用 npm start 啓動 Electron 即可。
最後附上 demo 源碼:https://github.com/AgoraIO/Agora-Web-Electron-Demo
更多產品信息、開發教程以及相關技術活動,請點擊「閱讀原文」獲取。
如開發中遇到問題,可訪問 RTC 開發者社區發帖提問