OpenVidu Front


Untitled

  1. OpenVidu 객체 가져오기
// --- 1) Get an OpenVidu object ( OpenVidu 객체 가져오기 )---

this.OV = new OpenVidu();

// --- 2) Init a session (세션 초기화 ) ---

this.setState({
    session: this.OV.initSession(),
    }, () => {
        // See next step
    }
);

  1. 관심 있는 세션 이벤트를 구독
// --- 3)
Specify the actions when events take place in the session
세션에서 이벤트가 발생할 때의 작업 지정. ---

var mySession = this.state.session;

    // On every new Stream received...
mySession.on('streamCreated', (event) => {
    // Subscribe to the Stream to receive it. Second parameter is undefined
    // so OpenVidu doesn't create an HTML video by its own
    var subscriber = mySession.subscribe(event.stream, undefined);

    //We use an auxiliar array to push the new stream
    var subscribers = this.state.subscribers;

    subscribers.push(subscriber);

    // Update the state with the new subscribers
    this.setState({
        subscribers: subscribers,
    });
});

    // On every Stream destroyed...
mySession.on('streamDestroyed', (event) => {
    event.preventDefault();

    // Remove the stream from 'subscribers' array
    this.deleteSubscriber(event.stream.streamManager);
});

// On every asynchronous exception...
mySession.on('exception', (exception) => {
    console.warn(exception);
});

// See next step

  1. 관심 있는 세션 이벤트를 구독한다 -> 구독할 세션을 백에서 내려준다.
  2. React 프레임워크를 사용할 때 원격 미디어 스트림을 관리하기 위한 좋은 접근 방식

-> 각 Subscriber객체에 공통 구성 요소를 공급하고 비디오를 관리하게 하는 것입니다. 이 구성 요소는 /UserVideoComponent/ 가 됩니다. 이렇게 하려면 수신한 각각의 새 구독자(subCriber)를 배열에 저장 subscribers해야 하고 필요할 때마다 삭제된 모든 구독자를 제거해야 합니다. 이를 달성하기 위해 다음 이벤트를 사용합니다.

  1. streamCreated: Session 객체가 수신한 각각의 새로운 Stream에 대해 구독하고

반환된 Subscriber 객체를 subscribers배열에 저장합니다.

  1. 메소드 session.subscribe가 두 번째 매개변수로 정의되지 않았으므로

OpenVidu는 자체적으로 DOM에 HTML 비디오 요소를 삽입하지 않습니다. (우리는 하위 구성요소 중 하나에 포함된 비디오 요소를 사용할 것입니다). AppComponent/ 의 HTML 템플릿은 각 구독자에 대해 /UserVideoComponent/ 를 선언하는 .map js 함수를 포함하기 때문에 새 비디오를 표시합니다 . 우리는 그것들을 실제로 Subscriber객체가 아니라 부모 클래스로 제공 StreamManager합니다. 이렇게 하면 /UserVideoComponent/Publisher 를 재사용하여 객체(StreamManager 클래스에서 상속됨) 도 표시 할 수 있습니다.

  1. 유효한 사용자 토큰으로 세션에 연결
 // --- 4) Connect to the session with a valid user token ---
 //유효한 사용자 토큰으로 세션에 연결

// 'getToken' method is simulating what your server-side should do.
// 'token' parameter should be retrieved and returned by your own backend
this.getToken().then(token => {

    // First param is the token got from OpenVidu Server. Second param can be retrieved by every user on event
    // 'streamCreated' (property Stream.connection.data), and will be appended to DOM as the user's nickname
    mySession.connect(token, { clientData: this.state.myUserName })
        .then(() => {

// --- 5) Get your own camera stream ---
//나만의 카메라 스트림 가져오기

            // Init a publisher passing undefined as targetElement (we don't want OpenVidu to insert a video
            // element: we will manage it on our own) and with the desired properties
            let publisher: Publisher = this.OV.initPublisher(undefined, {
                audioSource: undefined, // The source of audio. If undefined default microphone
                videoSource: undefined, // The source of video. If undefined default webcam
                publishAudio: true,     // Whether you want to start publishing with your audio unmuted or not
                publishVideo: true,     // Whether you want to start publishing with your video enabled or not
                resolution: '640x480',  // The resolution of your video
                frameRate: 30,          // The frame rate of your video
                insertMode: 'APPEND',   // How the video is inserted in the target element 'video-container'
                mirror: false           // Whether to mirror your local video or not
            });

// --- 6) Publish your stream ---
//		스트림 게시
            mySession.publish(publisher);

            // Set the main video in the page to display our webcam and store our Publisher
            this.setState({
                mainStreamManager: publisher,
                publisher: publisher,
            });
        })
        .catch(error => {
            console.log('There was an error connecting to the session:', error.code, error.message);
        });
});

메서드 에서 mySession.connect 첫 번째 매개변수는 최근에 검색된 사용자 토큰입니다. 두 번째 매개변수는 이벤트 시 모든 사용자가 event.stream.connection.data속성으로 받는 streamCreated값입니다 (이 값은 /UserVideoComponent/ 에서 사용자의 닉네임을 동영상에 추가하는 데 사용됨). 따라서 이 경우에는 값이 “myUserName”인 “clientData” 속성이 있는 객체이며, 이는 HTML 입력 <input className=“form-control” type=“textid=“userName” value={myUserName} onChange={this.handleChangeUserName} required />(사용자가 채움)에서 바인딩됩니다. 메서드가 성공하면 웹캠을 세션에 게시합니다. 이를 위해 Publisher원하는 속성을 가진 객체를 가져와 메서드를 통해 세션에 게시합니다 Session.publish(). 나머지 사용자는 Stream 개체를 수신하고 streamCreated이벤트를 실행합니다. 마지막으로 기본 비디오 플레이어(다른 /UserVideoComponent/ )가 기본적으로 Publisher 개체를 표시하도록 합니다. 다음은 메인 스트림 관리자를 표시할 HTML 코드입니다.

{this.state.mainStreamManager !== undefined ? (
    <div id="main-video" className="col-md-6">
        <UserVideoComponent streamManager={this.state.mainStreamManager} />
    </div>
) : null}

this.state.publisher그리고 상위 클래스인 , 아래에 Publisher를 저장합니다 StreamManager. 이렇게 하면 웹캠이 표시된 것과 동일한 방식으로 모든 원격 가입자를 따라 추가됩니다(모두 /UserVideoComponent/ 에 의해 표시됨을 기억하십시오 ).

{this.state.publisher !== undefined ? (
    <div className="stream-container col-md-6 col-xs-6">
        <UserVideoComponent streamManager={this.state.publisher}
         mainVideoStream={this.handleMainVideoStream} />
    </div>
) : null}