2

Basing my code in these two tutorials I found:

I´m trying to get the video´s frames and then convert them into blobs. But I haven´t been able to do it. This is the code I have made for the moment:

app.component.html

<div class="row">
    <button (click)="start()" class="btn btn-primary">Play</button>
  </div>

  <div class="row">
    <div class="col-md-12">
      <div class="text-center">
        <h3>
          <video #videoElement></video>
          <canvas #canvasElement style="overflow:auto"></canvas>
        </h3>
      </div>
    </div>
  </div>

app.component.ts

 import { Component } from '@angular/core';
import { ViewChild } from '@angular/core';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  @ViewChild('videoElement',  {static: true}) videoElement: any;  
  @ViewChild('canvasElement',  {static: true}) canvasElement: any;  
  video: any;
  canvas: any;

  ngOnInit() {
    this.video = this.videoElement.nativeElement;
    this.canvas = this.canvasElement.nativeElement;
  }

  start() {
    this.initCamera({ video: true, audio: false });
  }

  initCamera(config:any) {
    navigator.mediaDevices.getUserMedia(config).then(stream => {
      console.log(stream)
      this.video.srcObject = stream;
      this.video.play();
      this.canvas.width = this.video.videoWidth;
      this.canvas.height = this.video.videoHeight;
      this.canvas.getContext('2d').drawImage(this.video, 0, 0, this.video.videoWidth, this.video.videoHeight);  
      this.canvas.toBlob((blob) => {
        const img = new Image();
        console.log(blob);
        img.src = URL.createObjectURL(blob);
      });
    });
  }

}

My problem is that the callback´s argument blob is not having any value (null). So I wonder if anyone could help to solve this issue.

alberto vielma
  • 2,302
  • 2
  • 8
  • 15

1 Answers1

0

Reading the docs of MediaDevices.getUserMedia() and HTMLMediaElement.play() I noticed both of them return a Promise, therefore I used the syntax async-await to wait for the methods to finish and set the video, so I could catch the frames eventually and convert them into blobs.

Only change the method initCamera in the previous code I posted in the question:

async initCamera(config:any) {
     this.video.srcObject = await navigator.mediaDevices.getUserMedia(config);
     await this.video.play();
     this.canvas.width = this.video.videoWidth;
     this.canvas.height = this.video.videoHeight;
     this.canvas.getContext('2d').drawImage(this.video, 0, 0, this.video.videoWidth, this.video.videoHeight);
     this.canvas.toBlob((blob) => {
        const img = new Image();
        console.log(blob);
        img.src = URL.createObjectURL(blob);
      });
}
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
alberto vielma
  • 2,302
  • 2
  • 8
  • 15