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"

畫面示範


2017年7月6日 星期四

IONIC3的BarCodeScanner 簡易示範

  Ionic 經歷了angualr1~angualr2 終於邁向 ionic3,它的好夥伴angular 也發展到angular 4,雖然過去的來不及參與,但我們現在就可以參與最新的ionic APP的威力吧,我們就簡單的示範如何用最新的ionic3

步驟1: 確認node.js 是否最新版
C:\Users\joyce>ionic info
[WARN] You are not in an Ionic project directory. Project context may be missing.

global packages:

    @ionic/cli-utils : 1.0.0-rc.2
    Ionic CLI        : 3.0.0-rc.2

System:

    Node       : v7.10.0
    OS         : Windows 10
    Xcode      : not installed
    ios-deploy : not installed
    ios-sim    : not installed
之前無法順利升級的ionic3 原因在node.js 非最新版本,請各位多加注意

步驟2: 安裝ionic
npm install -g cordova ionic      

ionic start myApp tabs

cd myApp



步驟3:
ionic cordova plugin add phonegap-plugin-barcodescanner

npm install –save@ionic-native/barcode-scanner

步驟4: 引用ionic barcodeScanner的模組

路徑: App\app.module.ts
import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { BarcodeScanner } from '@ionic-native/barcode-scanner';

import { AboutPage } from '../pages/about/about';
import { BarcodePage } from '../pages/barcode/barcode';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    BarcodePage,
    HomePage,
    TabsPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    BarcodePage,
    HomePage,
    TabsPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    BarcodeScanner,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

【注意】 prviders:加入BarcodeScanner

ionic的新框架中的app.module.ts 有分為declartionsimportsetrycomponentsprivders 等,分別代表什麼意思?
  declarations: [
    MyApp,
    AboutPage,
    HomePage,
    TabsPage,
    BarcodePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    HomePage,
    BarcodePage,
    TabsPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    BarcodeScanner,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]


Declarations : 用來注入所有component的相關物件, 如同app.component.ts 或其客製的component.ts

EntryComponents : 根據ionic官方說法, 建立model時會事先編譯的組件,所以如果新建立componet,也會被宣告在這區塊中。


步驟5:建立一個新的分頁
ionic generate page barcode
自動在pages\產生barcode資料夾

產生的檔案

步驟6:修改barcode.html
<ion-header>

  <ion-navbar>
    <ion-title>barcodePage</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <button ion-button (click)="scan()">Scan</button>
</ion-content>

增加Button 並加上scan的事件


步驟7:修改barcode.ts
import { Component } from '@angular/core';
import { IonicPage } from 'ionic-angular';
import { BarcodeScanner } from '@ionic-native/barcode-scanner';

/**
 * Generated class for the BarcodePage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-barcode',
  templateUrl: 'barcode.html',
})
export class BarcodePage {

  constructor(private barcodeScanner: BarcodeScanner) {
  }

  scan(){
    console.log("enter scan");
      this.barcodeScanner.scan().then((barcodeData) => {
      // Success! Barcode data is here
      alert(barcodeData.text);
    }, (err) => {
      // An error occurred
    });
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad BarcodePage');
  }
}


這樣按下button就能自動取得QR-Code或二維條碼等資訊囉~