[react] OBS 프로그램, RTMP 서버로 Live Streaming!!

dev stefanCho·2021년 7월 16일
2

react

목록 보기
7/19

준비물 : obsproject에서 obs 프로그램을 다운로드

RTMP Server

1. rtmp server를 생성한다.

node-media-server의 README.md를 참고한다.

$ mkdir rtmpserver
$ cd rtmpserver
$ npm init --yes
$ npm install node-media-server

2. package.json의 script

  "scripts": {
    "start": "node index.js"
  }

3. index.js

node-media-server 문서에 있는 내용임

const NodeMediaServer = require('node-media-server');

const config = {
  rtmp: {
    port: 1935,
    chunk_size: 60000,
    gop_cache: true,
    ping: 30,
    ping_timeout: 60
  },
  http: {
    port: 8000,
    allow_origin: '*'
  }
};

var nms = new NodeMediaServer(config)
nms.run();

4. npm start

$ npm start

obs 설정

간단 설정
1. 스트리밍 Scene 이름을 추가해줌
2. 화면 (Display Capture), 소리 (Audio Input Capture)을 설정함, 화면 설정이 되지 않는 경우는 Mac 기준으로, Settings > Security & Privacy > Privacy > Screen Recording에서 OBS.app을 체크해주면 된다.
3. 스트리밍 Start, Stop
4. Settings 에서는 Stream > Server 셋팅, Output > Recording Path (파일 저장 위치) 등을 설정할 수 있다.

Client Server

아래 코드는 node-media-server 문서에 있는 내용으로, vanila js를 React js 형태로 변환한 것이다.

$ npm install flv.js
  • video tag의 ref를 (DOM Element) videoRef에 넣는다.
  • RTMP 서버에서는 localhost의 8000포트로 넘겨주게 된다.
import React from "react";
import { connect } from 'react-redux';
import flv from 'flv.js';
import { fetchStream } from '../../actions';

class StreamShow extends React.Component {
  constructor(props) {
    super(props);
    this.videoRef = React.createRef();
  }

  componentDidMount() {
    this.props.fetchStream(this.props.match.params.id);
    this.buildPlayer();
  }

  componentDidUpdate() {
    this.buildPlayer();
  }
  
  componentWillUnmount() {
    this.flvPlayer.destroy(); // 화면을 벗어나면 streaming 다운로드를 그만둔다.
  }

  buildPlayer() {
    // 이미 보고 있는 streaming이 있거나, 혹은 streaming이 없는 경우 return 한다. (streaming 최초 진입시에만 createPlayer를 하는 것임)
    if (this.flvPlayer || !this.props.stream) {
      return;
    }

    const { id } = this.props.stream;
    this.flvPlayer = flv.createPlayer({
        type: 'flv',
        url: `http://localhost:8000/live/${id}.flv`
    });
    this.flvPlayer.attachMediaElement(this.videoRef.current);
    this.flvPlayer.load();
  }
  
  render() {
    if (!this.props.stream) {
      return <div>Loading...</div>;
    }

    const { title, description } = this.props.stream;
    return (
      <React.Fragment>
        <video ref={this.videoRef} style={{ width: '100%' }} controls/>
        <h1>{title}</h1>
        <h4>{description}</h4>
      </React.Fragment>
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
    stream: state.streams[ownProps.match.params.id]
  }
}

export default connect(mapStateToProps, { fetchStream })(StreamShow);

결과


profile
Front-end Developer

0개의 댓글