1. 程式人生 > >跨平臺視頻通信項目-OpenTok

跨平臺視頻通信項目-OpenTok

視頻 音頻 即時通訊 webrtc opentok

1 理論知識

1.1 OpenTok平臺簡介

即時視頻通信日益成為主流服務,通過WebRTC,開發者可以輕松地將即時視頻通信功能加入到應用中。視頻聊天創業公司TokBox推出OpenTok,可實現瀏覽器與iOS設備間跨平臺視頻聊天。

OpenTok平臺可以輕松實現以下功能:

- 高質量的互動視頻

- 消息傳遞

- 屏幕分享

1.2 基本概念

1.2.1 客戶端SDK

一組可用於Web(JavaScript),IOS和Android的代碼庫,用於設置客戶端(處理大多數OpenTok的功能能),功能包括

- 發布會話中的流

- 訂閱會話中的流

- 監聽會話事件

1.2.2 服務器SDK

服務器SDK是部署於應用服務器上,可以使用Node,PHP,Java,.NET,Python和Ruby語言分裝OpenTok REST API,為客戶端生成新的會話和令牌。

1.2.3 OpenTok REST API

HTTP接口,通過調用該接口可以調用OpenTok服務器SDK的許多方法,其余創建會話和處理高級功能需要由OpenTok Cloud來完成,如歸檔和廣播。

1.2.4 OpenTok Cloud

管理會話,客戶端連接,API調用,信令,事件以及客戶端SDK或服務器SDK未處理的其他所有內容。

1.3 OpenTok該平臺包含庫

- Web client libraries(瀏覽器客戶端庫)

- IOS client libraries(IOS客戶端庫)

- Android client libraries(安卓客戶端庫)

- Server-Side SDKs(服務器端SDK)

- Server-Side REST API(服務器端REST接口)

1.4 系統架構

1.4.1 服務器

- 服務器端SDK支持語言有

-- Node

-- PHP

-- Java

-- .NET

-- Python

-- Ruby

- 服務器端功能生成憑據

1.4.2 客戶端

-- 處理大部分的OpenTok功能

-- 連接到會話

-- 將音頻視頻流發布到會話

-- 訂閱其他客戶端的流

1.5 功能闡述

技術分享

1.5.1 客戶端

-- 調用客戶端SDK

-- 從服務器獲取會話ID和令牌

-- 使用令牌連接到會話

-- 訂閱音頻視頻流

-- 監聽會話事件

1.5.2 應用服務器

- 調用服務器SDK

- 在OpenTok雲中創建會話

- 為客戶端生成令牌

- 向客戶端發送會話ID和令牌

1.5.3 會議

- OpenTok雲中的聊天室

- 將客戶端彼此連接

- 向客戶端發送時間

1.6 OpenTok的通訊過程分析

1.6.1 連接和發布訂閱

Step1 由應用服務器創建會話

技術分享

應用服務器調用OpenTok服務器SDK代碼,通過OpenTok REST API在雲中創建一個會話,並取得會話ID,將會議當做視頻聊天的房間。

Step2 客戶端加載應用程序,服務器創建令牌

技術分享

當用戶加載OpenTok Client SDK構建客戶端應用程序時,客戶端(網頁或移動應用程序)從服務器獲取會話信息(包括服務器創建的唯一身份驗證令牌,相當於客戶端與服務器校驗的密碼)

step3客戶端連接並開始流會話流

技術分享

- 客戶端使用會話ID和令牌建立會話連接

- 客戶端將音頻視頻流發布到會話並監聽重要事件(例如加入會話的新用戶)

step4 新的客戶端連接到會話

技術分享

- 當心用戶在單獨的網頁或移動端(客戶端2)中加載客戶端應用程序時

- 新客戶端從應用服務器連接收到會話ID和唯一的令牌

- 客戶端使用這些信息來建立會話連接。

step5 客戶訂閱對方的流

技術分享

- 新的客戶端連接到會話

- 客戶端2可以訂閱客戶端1的流

- 客戶端2將自己的視頻流發布到會中並且客戶端1訂閱該視頻流

- 兩個客戶端都一對一地訂閱對方視頻流,且兩端都在傾聽新的事件(如新的會話用戶)

1.7 開發中心的資源

1.7.1 Helo World

快速演示最基本的OpenTok功能。

https://tokbox.com/developer/quickstart/

1.7.2 教程

構建OpenTok應用程序並添加高級功能逐步演練。

https://tokbox.com/developer/tutorials/

1.7.3 代碼示例

使用示例應用程序GitHub repos列表,可幫助你更快地構建應用程序。

https://tokbox.com/developer/samples/

1.7.4 視頻聊天嵌入

以最少代碼將OpenTok功能集成到你的網站的最快方式。

https://tokbox.com/developer/embeds/

1.7.5 開發人員指南

有關所有OpenTok特點和功能的全面文檔,可參考關於Web,IOS和Android的客戶端SDK的特定類,方法和事件信息。

https://tokbox.com/developer/guides/

1.7.6 REST API參考文檔

使用OpenTok REST API和服務器SDK指南

https://tokbox.com/developer/rest/

1.7.7 開發人員工具

調試會話的有用工具和測試API調用等。

https://tokbox.com/developer/tools/

1.7.8 測試版程序

一個列出所有OpenTok公開Beta以及如何加入他們的頁面。

https://tokbox.com/developer/beta/

1.7.9 支持中心

如遇到問題找不到答案,請訪問支持中心。

https://support.tokbox.com/

2 實踐部分

2.1 部署環境

2.1.1 系統部署

1)最小化安裝CentOS 7.3 x86_64,系統信息如下

OS = CentOS 7.3 x86_64

IP Address = 10.168.0.55

HostName = openTok.cmdschool.org

2)名稱解析服務

Windows客戶端運行裏面輸入如下命令

notepad \Windows\System32\drivers\etc\hosts

並增加如下記錄

10.168.0.55 www.cmdschool.org

2.1.2 安裝nginx

yum install -y http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
yum install -y nginx

2.1.3 創建項目目錄

mkdir -p /usr/share/nginx/html/opentok

2.1.4 確認配置

cp /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/ssl_default.conf
vim /etc/nginx/conf.d/ssl_default.conf

確認存在如下內容:

server {
    listen       443;
    server_name  localhost;
    ssl on;
    ssl_certificate 1_www.cmdschool.org_bundle.crt;
    ssl_certificate_key 2_www.cmdschool.org.key;
    ssl_session_timeout 5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
    ssl_prefer_server_ciphers on;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

2.1.5 配置nginx服務

systemctl enable nginx
systemctl restart nginx

2.1.6 配置防火墻

firewall-cmd --permanent --add-service https
firewall-cmd –reload
firewall-cmd --list-all

2.1.7 nginx集成PHP fastCGI

1)安裝基礎軟件包

yum install -y php-fpm php

2)啟動並配置服務自啟動

systemctl enable php-fpm.service
systemctl start php-fpm.service

3)配置nginx集成php fastCGI

vim /etc/nginx/conf.d/ssl_default.conf

增加如下代碼

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        root           /usr/share/nginx/html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        /etc/nginx/fastcgi_params;
    }

重啟nginx服務

systemctl restart nginx

4)測試php fastCGI

添加調試代碼

echo ‘<?php phpinfo(); ?>‘ > /usr/share/nginx/html/index.php

訪問以下鏈接測試fastCGI

https://www.cmdschool.org/index.php

技術分享

5)如下日誌可以協助你排錯

tail -f /var/log/nginx/error.log
tail -f /var/log/php-fpm/error.log

2.1.8 安裝輔助工具包

yum install -y unzip

2.2 理解Web客戶端會話

2.2.1 配置Index頁引用OpenTok.js庫

vim /usr/share/nginx/html/opentok/index.html

輸入如下內容:

<html>
<body>
<!-- OpenTok.js library -->
<script src="https://static.opentok.com/v2/js/opentok.js"></script>
<script>

// credentials


// connect to session

  
// create subscriber


</script>
</body>
</html>

2.2.2 模擬創建服務器憑據

vim /var/www/html/opentok/index.html

內容加入到註釋“credentials”下:

var apiKey = ‘45828062‘;
var sessionId = ‘2_MX40NTgyODA2Mn5-MTQ5NzgzNTA0MjA1NX54WnZGd2VKc3JWTkF3aW04ZlBjTXpKTFV-UH4‘;
var token = ‘T1==cGFydG5lcl9pZD00NTgyODA2MiZzaWc9YjVlNjc2ZjJlOTgxOTY1YTJiNGQzMzc1NDZlZmRhYmViZDU1NTNlZjpzZXNzaW9uX2lkPTJfTVg0ME5UZ3lPREEyTW41LU1UUTVOemd6TlRBME1qQTFOWDU0V25aR2QyVktjM0pXVGtGM2FXMDRabEJqVFhwS1RGVi1VSDQmY3JlYXRlX3RpbWU9MTQ5NzgzNTEwMSZub25jZT0wLjA0NDA3NzI3NzgxOTc2MjY3JnJvbGU9cHVibGlzaGVyJmV4cGlyZV90aW1lPTE0OTc5MjE1MDE=‘;

註:必須由服務器創建有效的API秘鑰和會話以及令牌

2.2.3 模擬初始化會話

vim /var/www/html/opentok/index.html

內容加入到註釋“create subscriber”下:

var session = OT.initSession(apiKey, sessionId)
session.connect(token, function(error) {
 // create publisher
 

})

2.2.4 模擬發布視頻流

vim /var/www/html/opentok/index.html

內容加入到註釋“create publisher”下:

var publisher = OT.initPublisher();
   session.publish(publisher);

代碼允許你將網絡攝像頭和麥克風的音頻和視頻流發布到會話

2.2.5 創建訂閱

vim /var/www/html/opentok/index.html

內容加入到註釋“create publisher”下:

session.on(‘streamCreated‘, function(event) {
 session.subscribe(event.stream);
});

代碼允許你在會話中訂閱其他客戶端的視頻流

2.3 配置基本的客戶端

2.3.1 創建項目目錄結構

mkdir -p /usr/share/nginx/html/opentok/{js,css}

2.3.2 創建客戶端頁面

vim /var/www/html/opentok/index.html

加入如下內容:

<html>
<head>
    <title> OpenTok Getting Started </title>
    <link href="css/app.css" rel="stylesheet" type="text/css">
    <script src="https://static.opentok.com/v2/js/opentok.min.js"></script>
</head>
<body>

    <div id="videos">
        <div id="subscriber"></div>
        <div id="publisher"></div>
    </div>

    <script type="text/javascript" src="js/app.js"></script>
</body>
</html>

代碼作用如下:

- 引用openTok.js庫以及自己創建的JS和CSS文件

- 包含發布者與訂閱者的DIV

- 將包含視頻流

2.3.3 配置認證

vim /usr/share/nginx/html/opentok/js/app.js

加入如下內容:

// replace these values with those generated in your TokBox Account
var apiKey = "YOUR_API_KEY";
var sessionId = "YOUR_SESSION_ID";
var token = "YOUR_TOKEN";

// (optional) add server code here
initializeSession();

註:將2.2的apiKey/sessinoId/token值替換變量值。

2.3.4 連接會話並創建發布者

vim /usr/share/nginx/html/opentok/js/app.js

在當前代碼後面加入如下內容:

// Handling all of our errors here by alerting them
function handleError(error) {
  if (error) {
    alert(error.message);
  }
}

function initializeSession() {
  var session = OT.initSession(apiKey, sessionId);

  // Subscribe to a newly created stream

  // Create a publisher
  var publisher = OT.initPublisher(‘publisher‘, {
    insertMode: ‘append‘,
    width: ‘100%‘,
    height: ‘100%‘
  }, handleError);

  // Connect to the session
  session.connect(token, function(error) {
    // If the connection is successful, publish to the session
    if (error) {
      handleError(error);
    } else {
      session.publish(publisher, handleError);
    }
  });
}

代碼完成以下功能:

- initializeSession函數使用OT.initPubulisher方法創建一個publisher對象,該方法有三個參數, -- publisher視頻代替文檔對象模型的元素(指ID為publisher的DIV)

-- publisher屬性(insertMode/height/width屬性)

-- 指定完成錯誤處理

- initalizeSession方法創建一個session對象,該方法需要兩個參數,

-- apiKey,

-- sessionId

- session.connec方法將客戶端程序連接到openTok會話

- 如果連接openTok會話有錯誤,則將錯誤對象傳遞給connect事件處理程序(使用錯誤消息向控制臺發送console.error)

2.3.5 初始化用戶

vim /usr/share/nginx/html/opentok/js/app.js

在註釋後面加入如下內容:

// Subscribe to a newly created stream
session.on(‘streamCreated‘, function(event) {
  session.subscribe(event.stream, ‘subscriber‘, {
    insertMode: ‘append‘,
    width: ‘100%‘,
    height: ‘100%‘
  }, handleError);
});

- 在會話中創建新流,會話對象調度streamCreated事件。

- 客戶端檢測到流,我們使用session.subscribe()方法訂閱流,該方法需要四個參數,

-- 客戶端訂閱的Stream對象(event.stream)

-- 訂閱視頻代替文檔對象模型元素或ID(指ID為subscriber的DIV)

-- 訂閱視圖的外觀屬性(指inserMode,height,width屬性)

-- 錯誤處理函數(當subscribe方法返回成功或失敗時調用)

2.3.6 初始化用戶

vim /usr/share/nginx/html/opentok/css/app.css

在註釋後面加入如下內容:

body, html {
    background-color: gray;
    height: 100%;
}

#videos {
    position: relative;
    width: 100%;
    height: 100%;
    margin-left: auto;
    margin-right: auto;
}

#subscriber {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 10;
}

#publisher {
    position: absolute;
    width: 360px;
    height: 240px;
    bottom: 10px;
    left: 10px;
    z-index: 100;
    border: 3px solid white;
    border-radius: 3px;
}

2.4 服務器的部署安裝方式概述

2.4.1 選項一Heroku上啟動簡單的REST服務器

需要簡單部署請參閱以下鏈接:

https://heroku.com/deploy?template=https://github.com/opentok/learning-opentok-php

2.4.2 選項二使用服務器SDK構建(高定制)

需要高級定制請參閱:

https://tokbox.com/developer/sdks/server/

開發者指南請參閱:

https://tokbox.com/developer/guides/

SDK下載地址:

https://github.com/opentok/opentok-php-sdk/releases

PHP語言參考:

http://www.w3school.com.cn/php/php_syntax.asp

2.4.3 選項3服務器實例應用程序

需要實例程序部署請參閱:

https://tokbox.com/developer/samples/

2.5 使用SDK構建服務器

2.5.1 安裝composer

1)配置主程序

php -r "copy(‘https://getcomposer.org/installer‘, ‘composer-setup.php‘);"
php -r "if (hash_file(‘SHA384‘, ‘composer-setup.php‘) === ‘669656bab3166a7aff8a7506b8cb2d1c292f042046c5a994c43155c0be6190fa0355160742ab2e1c88d40d5be660b410‘) { echo ‘Installer verified‘; } else { echo ‘Installer corrupt‘; unlink(‘composer-setup.php‘); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink(‘composer-setup.php‘);"
mv composer.phar /usr/local/bin/composer

2)設置國內源

composer config repo.packagist composer https://packagist.phpcomposer.com

註:其他使用方式請參閱,

https://pkg.phpcomposer.com/

2.5.2 部署基礎包

cd /usr/share/nginx/html
mkdir backup
mv opentok backup
composer require opentok/opentok 2.3.1
composer require slim/slim 2.*
composer require gregwar/cache 1.0.*

配置基礎包的權限

chown -R nginx:apache /usr/share/nginx/html/

2.5.3 配置php-fpm的啟動腳本環境變量

cat /usr/lib/systemd/system/php-fpm.service | grep EnvironmentFile

確認包含如下參數:

EnvironmentFile=/etc/sysconfig/php-fpm

2.5.4 定義環境變量的參數

vim /etc/sysconfig/php-fpm

輸入如下配置:

API_KEY = 0000000
API_SECRET = abcdef1234567890abcdef01234567890abcdef

註:以上只是範例,API_KEY和API_SECRET需要到雲端註冊賬號申請。

https://tokbox.com/account

2.5.5 systemd的環境變量通過腳本傳給bash

1)配置變量傳遞腳本

vim /etc/profile.d/opentok.sh

輸入如下配置:

#!/bin/bash

if [ -f /etc/sysconfig/php-fpm ]; then
        oldifs=$IFS
        IFS=$‘\n‘
        for i in `cat /etc/sysconfig/php-fpm | egrep -v "^#|^$|^;" | sed ‘s/ //g‘`; do
                export "$i"
        done
        IFS=$oldifs
fi

2)導入bash的環境變量:

source /etc/profile

3)確認環境變量生效:

echo $API_KEY;echo $API_SECRET

顯示如下:

0000000
abcdef1234567890abcdef01234567890abcdef

2.5.6 將systemd環境變量傳給php-fpm

1)配置變量傳遞

vim /etc/php-fpm.d/www.conf

註釋後加入兩行傳參變量定義:

; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from
; the current environment.
; Default Value: clean env
;env[HOSTNAME] = $HOSTNAME
;env[PATH] = /usr/local/bin:/usr/bin:/bin
;env[TMP] = /tmp
;env[TMPDIR] = /tmp
;env[TEMP] = /tmp
env[API_KEY] = $API_KEY
env[API_SECRET] = $API_SECRET

2)通過PHPINFO函數檢查傳參

技術分享

註:配置方法詳見“2.1.7 nginx集成PHP fastCGI”

2.5.7 修改PHP.ini參數

註:以下全部修改配置文件“/etc/php.ini”,以下配置都需重啟“php-fpm”服務

1)顯示調試頁面

display_errors = stderr

2)屏蔽時區錯誤

date.timezone = "Asia/Shanghai"

2.5.8 代碼調試

測試以下鏈接的代碼:

https://www.cmdschool.org/vendor/opentok/opentok/sample/HelloWorld/web/index.php

如果有錯誤請根據提示修改:

vim vendor/opentok/opentok/sample/HelloWorld/web/index.php

2.6 部署項目Demo

2.6.1 下載Demo

如果你不想調試,請使用筆者已經調試過的demo,下載地址如下

http://down.51cto.com/data/2323312

2.6.2 將代碼下載到如下目錄

/usr/share/nginx/html

2.6.3 解壓

unzip opentok.zip

2.6.4 修改權限

chown -R nginx:apache /usr/share/nginx/html/opentok
chmod -R 770 /usr/share/nginx/html/opentok

2.6.5 準備調試環境

電腦中需插入如下設備:

- 攝像頭(可選)

- 麥克風(必須)

- 耳麥或音箱(可選)

2.6.6 測試運行

使用兩個以上的頁面打開如下地址:

https://www.cmdschool.org/opentok/index.php

可見如下窗口:

技術分享

參閱文檔:

===========================================

Tutorials

https://tokbox.com/developer/tutorials/


Set up a Basic Client (Start Here)

https://tokbox.com/developer/tutorials/web/basic-video-chat/


Web sample apps for PHP,

https://github.com/opentok/learning-opentok-php


Web sample apps for

https://github.com/opentok/opentok-web-samples


本文出自 “老譚linux集群博客” 博客,謝絕轉載!

跨平臺視頻通信項目-OpenTok