2017年9月18日 星期一

Angular2 簡易版的webRTC

html5推出webrtc的線上影音串流,我們就能立即取得即時視訊,但門檻仍高,
所以有人佛心來研究這款好用的工具peer.js 簡化複雜認證過程,我就簡單示範一下。

一、下戴相關Peer.jsjavaScript

將其檔案放置assets/js

二、修改anguar-cli.json
scripts區塊中引用
      "scripts": [
        "./assets/js/peer.min.js"
      ],

default的區塊中設定IP Port
"defaults": {
    "styleExt": "css",
    "component": {},
     "serve": {
      "port": 4300,
      "host": "192.168.4.88"
     }

三、使用Peer.js 的範例

修改 app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule }   from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

修改app/app.component.html
<h1>My id - {{mypeerid}}</h1>
<input type="text" [(ngModel)]="anotherid">
<button (click)="connect()">Connect</button>
<button (click)="videoconnect()">VideoChat</button>
<video #myvideo></video>

修改app/app.component.ts
import { Component, OnInit,ViewChild} from '@angular/core';
declare var Peer: any;
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  title = 'app';
  mypeerid: any;
  peer;
  anotherid;
  @ViewChild('myvideo') myVideo: any; //取得htmlvideo元素IDmyvideo

  ngOnInit() {
    let video = this.myVideo.nativeElement;
//建立peer物件,如需建立https 才能跨電腦取得對方的視訊
    this.peer = new Peer({ host: 'peerjs-server.herokuapp.com', secure: true, port: 443 })
    //建立逾期時間,如果太久自動失效
setTimeout(() => {
      this.mypeerid = this.peer.id;
    }, 3000);
    //接受連線
    this.peer.on('connection', function (conn) {
     //取得資料
      conn.on('data', function (data) {
        console.log(data);
      });
    });
 
    var n = <any>navigator;
    n.getUserMedia = (n.getUserMedia || n.webkitGetUserMedia || n.mozGetUserMedia || n.msGetUserMedia);
    //回應另一端電腦所建立Peer連線
   this.peer.on('call', function(call) {
      n.getUserMedia({video: true, audio: true}, function(stream) {
        call.answer(stream); //回傳本機端的視訊或聲音
        //取得遠端電腦傳回的視訊或聲音
        call.on('stream', function(remotestream){ 
          video.src = URL.createObjectURL(remotestream);
          video.play();
        })
      }, function(err) {
        console.log('Failed to get stream', err);
      })
    })
 }

  connect() {
    var conn = this.peer.connect(this.anotherid); //與遠端電腦建立peer連線
    conn.on('open', function () {
      conn.send('Message from that id');
    });
  }

  videoconnect(){
    let video = this.myVideo.nativeElement;
    var localvar = this.peer;
    var fname = this.anotherid;
    var n = <any>navigator;
   
    n.getUserMedia = ( n.getUserMedia || n.webkitGetUserMedia || n.mozGetUserMedia  || n.msGetUserMedia );
   
    n.getUserMedia({video: true, audio: true}, function(stream) {
      var call = localvar.call(fname, stream); //與遠端電腦建立peer連線
call.on('stream', function(remotestream) {
        video.src = URL.createObjectURL(remotestream); //取得遠端電腦資訊
        video.play();
      })
    }, function(err){
      console.log('Failed to get stream', err);
    })
  }
}

四、安裝openSSL



五、啟動專案

啟動WebRTC需要有https的協定下,所以需要建立自我憑證的金鑰

ng serve --ssl 1 --ssl-key "D:\joyce\angular2\angularWebRTC\cert\private.key" --ssl-cert "D:\joyce\angular2\angularWebRTC\cert\mycert.crt"

畫面示範


沒有留言:

張貼留言