使用 WebRTC 和 Twilio 創建實時視頻聊天室

興趣編程網 發佈 2022-05-07T17:53:41.112926+00:00

我們先將本篇文章的代碼貢獻出來,讓大家可以進行測試使用,地址:https://url99.ctfile.com/f/33882099-576968789-9adcb7?

我們先將本篇文章的代碼貢獻出來,讓大家可以進行測試使用,地址:

https://url99.ctfile.com/f/33882099-576968789-9adcb7?p=5496 (訪問密碼:5496)

回顧一下,WebRTC 旨在為 Web 和移動開發人員提供使用簡單 API 創建高清視頻和音頻呼叫的能力。許多跨越所有行業的大大小小的公司,包括但不限於醫療保健、教育、客戶服務、專業服務和社交媒體,都在利用 WebRTC 構建下一代應用程式。

您可能已經使用了這項技術,甚至沒有意識到它。如果您使用過 Facebook Messenger、WhatsApp 和/或 SnapChat 視頻或語音功能,則您在不知不覺中使用 WebRTC 與您的家人和朋友交流。

快速啟動開發

WebRTC 和其他類似的網絡技術正在改變人們以各種方式進行交流和參與的方式。開發人員正在提供可輕鬆集成到任何應用程式中的增強通信。正如 Facebook、SnapChat、Tango 和 WhatsApp 等公司正在將實時音頻和視頻功能集成到他們的應用程式中一樣,您也可以。

您可能會驚訝於這樣做的過程是簡單、快速且最具成本效益的。由於這項偉大的技術是由 Google 開源的,因此您現在可以免費構建您的應用程式,而無需支付許可費用。但是,如果您不熟悉 WebRTC 所需的一些常用組件,例如TURN / STUN、信令、多點會議單元 (MCU)等,那麼構建自己的解決方案的道路可能會非常艱巨。

在我們的行業中,有超過 20 個平台即服務 (PaaS) 提供商提供 WebRTC 解決方案。在獲得了多年使用這項技術的經驗後,我們(在 Blacc Spot Media)擁有一些最受歡迎的 PaaS 提供商,這些提供商已被證明可以很好地為我們的客戶服務。我們與許多供應商合作,以縮短將客戶產品快速推向市場所需的開發時間。我們有機會與之合作的供應商之一是 Twilio。在本文中,我們將重點關注他們的平台。

Twilio 視頻

如果您不熟悉Twilio,它們通過一組簡單的 API 和 SDK 提供了一套通信工具。他們的解決方案使開發人員能夠將實時通信功能添加到他們的應用程式中。Twilio 武器庫的新功能是可編程視頻,它允許您在移動和 Web 應用程式中創建高清多方視頻和音頻體驗。Twilio 是 WebRTC 行業的資深人士,正在擴展其當前的 Twilio Client 產品,該產品的核心已經運行了一些 WebRTC 組件。Twilio Video 擁有光明的未來,其完整的增強路線圖正在開發中。很快您將能夠體驗移動屏幕共享以及增強的多方功能。

建立一個聊天室

您將需要一個 Twilio 帳戶才能使用此演示。如果您還沒有,您現在可以註冊 一個免費帳戶。確保您選擇「可編程視頻」作為您計劃使用的第一個服務。創建帳戶後,您將需要以下信息來創建應用程式:

證書

描述

Twilio 帳戶 SID

您的主要 Twilio 帳戶標識符 -在您的儀錶板上找到它。

Twilio 視頻配置 SID

向訪問令牌添加視頻功能 -在此處生成一個

API 密鑰

用於驗證 -在此處生成一個。

API 秘密

用於身份驗證 -就像上面一樣,你會在這裡得到一個。

我們還將使用Firebase作為一種簡單的方法來跟蹤哪些用戶可以聊天。Firebase 是一種移動後端即服務,可為您的應用後端提供支持,包括數據存儲、用戶身份驗證、靜態託管等。如果您沒有帳戶,請註冊一個免費帳戶以開始使用。完成這些說明後,您將能夠將此演示上傳到伺服器以運行實時視頻聊天室。

演示

如果您將此演示部署到 Web 伺服器,請務必注意,從 Chrome 47 開始,需要 SSL 加密域才能訪問用戶的麥克風和攝像頭。解決此問題的一個簡單方法是使用新的 Let's Encrypt服務安裝免費證書。您可以在Digital Ocean找到一個關於如何在您的伺服器上安裝證書的好教程 。

PHP

為了訪問 Twilio 平台,您必須首先在系統中進行身份驗證。在這個例子中,我們在伺服器端使用 PHP 來快速啟動和運行。Twilio 具有廣泛的伺服器端庫以滿足您的偏好。進行身份驗證後,我們會傳遞您從上面的 Twilio 帳戶收到的帳戶憑據。

// ADD TWILIO REQURIED LIBRARIES
require_once('twilio/Services/Twilio.php');

// TWILIO CREDENTIALS
$TWILIO_ACCOUNT_SID = 'your account sid here';
$TWILIO_CONFIGURATION_SID = 'your configuration sid here';
$TWILIO_API_KEY = 'your API key here';
$TWILIO_API_SECRET = 'your API secret here';

// CREATE TWILIO TOKEN
// $id will be the user name used to join the chat
$id = $_GET['id'];

$token = new Services_Twilio_AccessToken(
    $TWILIO_ACCOUNT_SID,
    $TWILIO_API_KEY,
    $TWILIO_API_SECRET,
    3600,
    $id
);

// GRANT ACCESS TO CONVERSTATION
$grant = new Services_Twilio_Auth_ConversationsGrant();
$grant->setConfigurationProfileSid($TWILIO_CONFIGURATION_SID);
$token->addGrant($grant);

// JSON ENCODE RESPONSE
echo json_encode(array(
    'id'    => $id,
    'token' => $token->toJWT(),
));

HTML

此演示的 HTML 代碼非常簡單,包括使用您的姓名連接到聊天室並查看可用於聊天的完整用戶列表以及事件日誌的功能。

<div class="m-content">
    <h1>Quick Start Your WebRTC Project with Twilio</h1>
    <div class="start">
        <input type="text" id="id" name="id" value="" placeholder="Enter your name to join the chat" />
        <button id="start">Join Chat Room</button>
        <button id="disconnect" class="b-disconnect hide">Disconnect from Chat</button>
        <div class="status">
            <strong>MY STATUS:</strong> <span id="status">DISCONNECTED</span>
        </div>
    </div>
    <div class="local">
        <div id="lstream"></div>
    </div>
    <div class="remote">
        <div id="rstream"></div>
    </div>
    <div class="users-list"></div>
    <div class="logs"></div>
</div>
<script src="https://code.jQuery.com/jquery-1.9.1.min.js"></script>
<script src="https://media.twiliocdn.com/sdk/js/common/v0.1/twilio-common.min.js"></script>
<script src="https://media.twiliocdn.com/sdk/js/conversations/v0.13/twilio-conversations.min.js"></script>
<script src="https://cdn.firebase.com/js/client/2.4.0/firebase.js"></script>
<script src="app.js"></script>

JavaScript

第一件事。確保用戶使用兼容的 WebRTC 瀏覽器進行連接非常重要。

if (!navigator.webkitGetUserMedia && !navigator.mozGetUserMedia) {
    tlog('You are using a browser that is not WebRTC compatible, please use Google Chrome or Mozilla Firefox', true);
}

我們正在使用一個函數tlog()來向用戶發送狀態消息。如果發生錯誤,我們將 HTML 字符串msg連同設置一起發送到參數etrue

function tlog(msg, e) {
  if (e) {
    $('.logs').append('<div class="log error">' + msg + '</div>');
  } else {
    $('.logs').append('<div class="log">' + msg + '</div>');
  }
}

現在我們知道用戶正在使用兼容的瀏覽器進行連接,我們將使用 jQuery 在用戶準備好加入聊天時添加點擊事件。然後,我們將向我們的伺服器端token.php生成文件發送一個 Ajax 請求id,其中用戶連接到聊天室。

在此演示中,我們使用用戶在文本欄位中輸入的名稱。在我們收到我們的令牌後,我們將它傳遞給Twilio.AccessManager以創建一個new Twilio.Conversations.client,它將為我們提供一組使用Promise.

$('#start').on('click', function() {
  if ($('#id').val() == '') {
    tlog('Please enter a name to join the chat', true);
  } else {
    id = $('#id').val().replace(/\s+/g, '');
    $.ajax({
      type: 'POST',
      url: 'token.php',
      data: {
        id: $('#id').val()
      },
      dataType: "json",
      success: function(data) {

        /* We pass the provided access token to the accessManager */
        var accessManager = new Twilio.AccessManager(data.token);
        conversationsClient = new Twilio.Conversations.Client(accessManager);
        conversationsClient.listen().then(clientConnected, function(e) {
          tlog('Could not connect to Twilio: ' + e.message, true);
        });
      }
    });
  }
});

在我們收到來自 的成功連接響應後new Twilio.Conversations.Client,我們將調用該clientConnected()函數以及firebaseConnect()。您將需要從您的帳戶添加 Firebase 網址以存儲所有可用用戶。我們還將為 Firebase 添加一些事件偵聽器,以跟蹤用戶何時連接和離開聊天。

function clientConnected() {
  firebaseConnect();
  $('#id, #start').hide();
  $('#disconnect').fadeIn();
  $('#status').css({ 'color': '#5E9F21' }).text('CONNECTED');
  tlog('You have succussfully connected to this Twilio chat room as <strong>' + id + '</strong>.');
  if (!lmedia) {
    startConversation();
  };
  conversationInvite();
}

function firebaseConnect(){
  var fburl = '...add your firebase url here...';
  firebase = new Firebase(fburl + '/users');
  var uid = firebase.push(id);
  fid = uid.toString();

  new Firebase(fid)
    .onDisconnect()
    .remove();

  firebase.on('child_added', function(child) {
    addParticipant(child);
  });

  firebase.on('child_removed', function(child) {
    $('.' + child.val()).remove();
  });
}

function addParticipant(child) {
  if (child.val() != id) {
    var markup = '<div class="user ' + child.val() + '"><span>'
               + child.val() + '</span><button class="b-connect" id="'
               + child.val() + '">Call Now</button></div>';
    $('.users-list').append(markup);
  }
}

現在來看看 WebRTC 的魔力吧!new Twilio.Conversations.LocalMedia()我們通過調用流並將其附加到 HTML 元素來訪問用戶的麥克風和攝像頭。請注意:您需要授予對麥克風和攝像頭的訪問權限。

function startConversation() {
  lmedia = new Twilio.Conversations.LocalMedia();
  Twilio.Conversations.getUserMedia().then(function(mediaStream) {
    lmedia.addStream(mediaStream);
    lmedia.attach('#lstream');
  }, function(e) {
    tlog('We were unable to access your Camera and Microphone.');
  });
}

接下來,我們為聊天室中其他用戶的傳入邀請添加一個事件偵聽器。我們添加invite.accept().then(conversationStarted)了允許自動連接。在您的應用程式中,您可能希望在連接之前先提示其他用戶。請注意:您需要允許每個其他用戶訪問您的攝像頭和麥克風。

function conversationInvite() {
  conversationsClient.on('invite', function(invite) {
    invite.accept().then(conversationStarted);
    tlog('You have a incoming invite from: <strong>' + invite.from + '</strong>');
  });
}

加入聊天后,您會Call Now在每個可在聊天室中聊天的用戶旁邊看到一個按鈕。單擊按鈕以連接到用戶。

我們會將我們當前的本地媒體流傳遞給我們options.localMedia邀請聊天的人。

$(document).on('click', '.b-connect', function() {
    var user = $(this).attr('id');
    var options = {};
    options.localMedia = lmedia;
    conversationsClient
      .inviteToConversation(user, options)
      .then(conversationStarted, function(error) {
        tlog('We were unable to create the chat conversation with that user, try another online user.', true);
      });
});

接受傳入邀請後,我們將連接並開始對話。

function conversationStarted(convo) {
  conversation = convo;
  tlog('We are waiting on your friend to connect...');
  participantConnected();
  participantDisconnected();
}

接下來,我們participantConnected()為連接到對話的所有參與者添加帶有事件偵聽器的函數。當其他用戶加入時,我們使用participant.media.attach('#rstream').

function participantConnected() {
  conversation.on('participantConnected', function(participant) {
    new Firebase(fid).remove();
    participant.media.attach('#rstream');
    tlog('You are connected with: <strong>' + participant.identity + '</strong>');
  });
}

最後,我們在函數中為所有與對話斷開連接的參與者添加一個事件監聽器participantDisconnected()。它使我們能夠跟蹤任何斷開連接並成功地將用戶從聊天室中刪除。

function participantDisconnected() {
  conversation.on('participantDisconnected', function(participant) {
    if (!disconnected) {
      var uid = firebase.push(id);
      fid = uid.toString();
      new Firebase(fid).onDisconnect().remove();
    }

    $('.' + participant.identity).remove();
    tlog('<strong>' + participant.identity + '</strong> has disconnected from this chat.');
    $('.users-list').empty();

    if (firebase) {
      firebase.once('child_added', function(child) {
        addParticipant(child);
      });
    }
  });
}

我們為用戶提供了一種手動斷開聊天室連接並重置為默認狀態的方法。我們會從 Firebase 清除用戶的可用性,以便其他用戶在用戶重新聯機之前無法連接。接下來,我們停止將媒體流傳輸到對話中,並停止共享對我們的麥克風和攝像頭的訪問。

$('#disconnect').on('click', function() {
  new Firebase(fid).remove();
  firebase.off();
  firebase = null;
  disconnected = true;
  $('#disconnect').hide();
  $('#start, #id').fadeIn();
  $('#status').css({
    'color': ''
  }).text('DISCONNETED');
  $('.users-list').empty();
  stopConversation();
});

function stopConversation() {
  if (conversation) {
    conversation.disconnect();
    conversationsClient = null;
    conversation = null;
    lmedia.stop();
    lmedia = null;
    tlog('You have successfully disconnected from this chat conversation, start another one now.');
  } else {
    lmedia.stop();
    lmedia = null;
    tlog('Please rejoin the chatroom to start a conversation.');
  }
}

webrtc.tutorials。

如果您對其他 PaaS 提供商的其他教程感興趣,Blacc Spot Media 將推出一個名為webrtc.tutorials的新網站。該站點還將提供提示和技巧,以使用 WebRTC 增強您的應用程式內的通信。

結論

隨著 WebRTC 的優勢和功能的發展,我們將看到它改變了我們看待通信的方式。正如消息應用程式在用戶數量方面已經取代了傳統的社交媒體網絡一樣,WebRTC 將增強全球公司和組織可用的基本消息傳遞功能。Twilio 和 Firebase 使開發人員可以輕鬆地構建像這樣的實時通信應用程式部署。你的下一步是什麼?當然要建立偉大的東西!

關鍵字: