9분 이내에 JavaScript 및 Twilio CLI로 비디오 애플리케이션 구축
26309 단어 htmlvideotwiliojavascript

우리 중 많은 사람들이 현재 원격 근무를 하고 있으며, 영상 채팅은 현재 매우 유행하고 있다.자바스크립트Twilio Programmable Video와 Twilio Serverless Toolkit를 9분 안에 사용하여 화상 채팅방을 시작하고 실행하는 방법을 소개합니다.

설치 프로그램
Twilio 프로그래밍 가능한 비디오 어플리케이션을 구축하려면 다음이 필요합니다.
twilio plugins:install @twilio-labs/plugin-serverless
그런 다음 실행twilio serverless
서버 없는 항목 만들기
명령줄에서 실행하여 빈 템플릿을 사용하여 서버 없는 항목 만들기
twilio serverless:init --template blank {insert-project-name}
프로젝트 이름으로 바꾸기 {insert-project-name}
- 저는 제 tfvideo
라고 합니다.명령이 완료되면 현재 디렉토리에 프로젝트 이름이 있는 디렉토리가 생성됩니다.프로젝트 디렉터리에는 기존 폴더가 포함되어 있습니다.
functions
에 video-token.js
라는 파일을 추가하고 자원에 두 개의 파일을 추가합니다: video.html
및index.js
..env
에서 환경 변수를 설정합니다.ACCOUNT_SID
및 AUTH_TOKEN
을 포함하는 앞의 두 줄을 단독으로 유지할 수 있습니다.이들 아래에 계정 SID, API 키 및 API 기밀을 추가합니다.
액세스 토큰을 생성합니다.
functions/video-token.js
에서 다음 코드를 추가하여 접근 영패를 생성합니다.여기에서 우리는 모든 사용자에게 환경 변수, 고정된 방 이름과 ACCESS_TOKEN_IDENTITY
을 설정합니다.모든 사용자는 방에 접근할 권리가 있다tf
.이 코드는 this page which also contains more information on Access Tokens 에서 수정되었습니다.exports.handler = function(context, event, callback) {
const TWILIO_ACCOUNT_SID = context.TWILIO_ACCOUNT_SID;
const TWILIO_API_KEY = context.TWILIO_API_KEY;
const TWILIO_API_SECRET = context.TWILIO_API_SECRET;
const ACCESS_TOKEN_IDENTITY =
Math.random()
.toString(36)
.substring(2, 15) +
Math.random()
.toString(36)
.substring(2, 15); // random client name
const ROOM_NAME = 'tf'; // fixed room name
const AccessToken = Twilio.jwt.AccessToken;
const VideoGrant = AccessToken.VideoGrant;
// only tokens are available for participating rooms
// Create a Video grant enabling client to use Video, only for this room
const videoGrant = new VideoGrant({
room: ROOM_NAME
});
//Create an access token to sign and return to the client with the grant we just created
const accessToken = new AccessToken(
TWILIO_ACCOUNT_SID,
TWILIO_API_KEY,
TWILIO_API_SECRET
);
accessToken.addGrant(videoGrant); //Add the grant to the token
accessToken.identity = ACCESS_TOKEN_IDENTITY;
callback(null, {
token: accessToken.toJwt() //Serialize the token to a JWT string
});
};
저희 동영상 사이트를 만들겠습니다.
이전에 생성한 빈 파일
assets/video.html
을 엽니다.방에 들어가거나 나가는 단추, 사용자 카메라의 미리 보기를 자동으로 표시하는 비디오 라벨, 우리가 작성하고자 하는 index.js
파일, Axios와 Twilio 동영상을 포함한 간단한 HTML을 작성할 것입니다.js 라이브러리:<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Twilio Video Serverless Demo</title>
</head>
<body>
<div id="room-controls">
<video id="video" autoplay muted="true" width="320"
height="240"></video>
<button id="button-join">Join Room</button>
<button id="button-leave" disabled>Leave Room</button>
</div>
<script src="//media.twiliocdn.com/sdk/js/video/releases/2.3.0/twilio-video.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
<script src="index.js"></script>
</body>
</html>
비디오 애플리케이션 구축
assets/index.js
에 다음 코드를 추가합니다.즉, 복사하여 붙여넣을 수 있는 스크립트는 다음과 같습니다.axio
파일을 호출하여 접근 영패를 생성합니다video-token
또는 tf
을 클릭하면 button-join
룸에 연결하고 연결 해제button-leave
채팅방에 원격 참여자의 곡을 구독하거나 구독을 취소하여 원격 참여자의 영상을 표시합니다.만약 그것들이 이미 방에 있다면, 우리는 기존의 tf
을 교체하고, 사건 탐지기를 participants
에 추가합니다.(() => {
'use strict';
const TWILIO_DOMAIN = location.host; //unique to user, will be website to visit for video app
const ROOM_NAME = 'tf';
const Video = Twilio.Video;
let videoRoom, localStream;
const video = document.getElementById("video");
// preview screen
navigator.mediaDevices.getUserMedia({video: true, audio: true})
.then(vid => {
video.srcObject = vid;
localStream = vid;
})
// buttons
const joinRoomButton = document.getElementById("button-join");
const leaveRoomButton = document.getElementById("button-leave");
var site = `https://${TWILIO_DOMAIN}/video-token`;
console.log(`site ${site}`);
joinRoomButton.onclick = () => {
// get access token
axios.get(`https://${TWILIO_DOMAIN}/video-token`).then(async (body) => {
const token = body.data.token;
console.log(token);
Video.connect(token, { name: ROOM_NAME }).then((room) => {
console.log(`Connected to Room ${room.name}`);
videoRoom = room;
room.participants.forEach(participantConnected);
room.on("participantConnected", participantConnected);
room.on("participantDisconnected", participantDisconnected);
room.once("disconnected", (error) =>
room.participants.forEach(participantDisconnected)
);
joinRoomButton.disabled = true;
leaveRoomButton.disabled = false;
});
});
};
leaveRoomButton.onclick = () => {
videoRoom.disconnect();
console.log(`Disconnected from Room ${videoRoom.name}`);
joinRoomButton.disabled = false;
leaveRoomButton.disabled = true;
};
})();
const participantConnected = (participant) => {
console.log(`Participant ${participant.identity} connected'`);
const div = document.createElement('div');
div.id = participant.sid;
participant.on('trackSubscribed', track => trackSubscribed(div, track));
participant.on('trackUnsubscribed', trackUnsubscribed);
participant.tracks.forEach(publication => {
if (publication.isSubscribed) {
trackSubscribed(div, publication.track);
}
});
document.body.appendChild(div);
}
const participantDisconnected = (participant) => {
console.log(`Participant ${participant.identity} disconnected.`);
document.getElementById(participant.sid).remove();
}
const trackSubscribed = (div, track) => {
div.appendChild(track.attach());
}
const trackUnsubscribed = (track) => {
track.detach().forEach(element => element.remove());
}
네, 이것은 이미 프로그래밍 영상에 의해 해혹되고 간소화되었습니다!명령줄에서 실행
trackSubscribed
.CLI는 서버 없는 프로젝트와 기타 배포 세부 사항을 성공적으로 배포한 것을 축하합니다.자동으로 생성된 자산과 함께 배치된 twilio serverless:deploy
을 삭제하거나 무시할 수 있습니다.functions/blank.js
아래의 video.html
URL을 캡처하여 당신의 친구와 공유하고, 그리고tada!빠른 영상통화가 필요할 때 자신의 영상실을 사용하고 공유할 수 있습니다.
이 응용 프로그램은 매우 간단하지만, CSS를 작성하지 않은 것을 고려하면, 그것은 절대로 괜찮다. 그렇지?전체 코드는 found here on GitHub 일 수 있습니다.
다음은 무엇입니까
Twilio의 서버 없는 패키지는 응용 프로그램을 쉽게 호스팅하고 신속하게 시작하고 실행할 수 있습니다.다음은 더 많은 CSS를 작성해서 응용 프로그램을 미화하고 programmable chat feature 또는 more Twilio Video features 을 추가하며 사용자 이름을 얻고 채팅할 때 표시할 수 있습니다.인터넷이나 댓글로 무엇을 구축하고 있는지 알려주세요.
](
Reference
이 문제에 관하여(9분 이내에 JavaScript 및 Twilio CLI로 비디오 애플리케이션 구축), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/twilio/build-a-video-app-with-javascript-and-the-twilio-cli-in-9-minutes-4fol텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)