Troubles encountered while trying to make MediaRecorder function in Angular 9

Recently, I've been working on integrating Media Recorder into my Angular 9 application by following the instructions provided at this link. However, I have encountered some issues along the way.

When I access the page with the Media Recorder component, I notice that my camera light turns on, indicating that it has been detected. However, all I see below is a blank space:

https://i.stack.imgur.com/FdO2G.png

None of the buttons seem to be functional and I am unsure as to why this might be happening.

Upon checking my console log, I came across the following:

https://i.stack.imgur.com/IA7Y2.png

I would appreciate any insights you could offer after reviewing my mediarecorder.ts component code:

/// <reference types="@types/dom-mediacapture-record" />

import { Component, OnInit, AfterViewInit } from '@angular/core';
import {PatientsService} from '../patients.service';

// declare var MediaRecorder:any;

@Component({
  selector: 'app-mediarecord',
  templateUrl: './mediarecord.component.html',
  styleUrls: ['./mediarecord.component.scss']
})
export class MediarecordComponent implements AfterViewInit,OnInit  {

  constraints; video; mediaRecorder; options;

  private recordedChunks: any[] = [];
  streams: string[] = [];
  audioChunks: any[];
  videoChunks: any[];

  constructor(private signalHub: PatientsService) 

  {
    this.constraints = { audio: true, video: true };
  }

  ngOnInit() {
    // const video = document.createElement('video');
    // this.video = document.getElementsByClassName('video')[0];
    // console.log(this.video);
  }
  
  ngAfterViewInit() {
    this.runMedia();
  }

  successCallback(stream) {
    if (MediaRecorder.isTypeSupported('video/webm;codecs=vp9')) {
    this.options = { mimeType: 'video/webm; codecs=vp9' };
    console.log("Oh no");
    } else if (MediaRecorder.isTypeSupported('video/webm;codecs=vp8')) {
      this.options = { mimeType: 'video/webm; codecs=vp8' };
    } else {
      // ...
    }

    this.mediaRecorder = new MediaRecorder(stream, this.options);
    console.log(this.mediaRecorder);
    console.log(this.options);

    this.mediaRecorder.ondataavailable = this.handleDataAvailable;
    
    this.mediaRecorder.start();
    console.log(this.mediaRecorder);

    console.log("oo");
  }

  stopVideo() {
    this.mediaRecorder.stop();
  }

  handleDataAvailable(blob) {
    console.log(blob);
    this.recordedChunks.push(blob.data);
  }

  errorCallback(error) {
    console.log('navigator.getUserMedia error: ', error);
  }

  runMedia() {

    this.streams.push("f");
    console.log(this.constraints);

    navigator.mediaDevices.getUserMedia(this.constraints)
      .then((stream) => {
         console.log(stream);
        this.successCallback(stream);
      })
      .catch(this.errorCallback);
  }

}

In my HTML file, I understand that I need methods to bind these functionalities with the TypeScript component:

<video id="Recording" width="800" height="400" playsinline autoplay ></video>

    <div>
        <button id="start" (click) = "ngAfterViewInit()" >Start camera</button>
        <button id="record" >Start Recording</button>
        <button id="play" >Play</button>
        <button id="download">Download</button>
    </div>

    <div>
        <h4>Media Stream Constraints options</h4>
        <p>Echo cancellation: <input type="checkbox" id="echoCancellation"></p>
    </div>

    <div>
        <span id="errorMsg"></span>
    </div>

Additionally, I have an index.d.ts file providing type definitions for w3c MediaStream Recording 1.0, and a lib.dom.ts file obtained via npm install @types/dom-mediacapture-record.

Answer №1

To execute the "runMedia()" method when the "start" button is clicked, you can directly call it from the HTML instead of using the "ngAfterViewInit()" hook.

<video id="Recording" width="800" height="400" playsinline autoplay ></video>

    <div>
        <button id="start" (click)="runMedia()">Start camera</button>
        <button id="record">Start Recording</button> // call record method
        <button id="play">Play</button> // call play method
        <button id="download">Download</button> // call download method
    </div>

    <div>
        <h4>Media Stream Constraints options</h4>
        <p>Echo cancellation: <input type="checkbox" id="echoCancellation"></p>
    </div>

    <div>
        <span id="errorMsg"></span>
    </div>

By following this approach, you should be able to trigger the "runMedia()" method by clicking on the start button. If you could provide a plunker or stackblitz showcasing your code, it would greatly assist in understanding the issue as a whole.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fetch the JSON data and pass it to the ITest

Objective: Retrieve data from a JSON file and store it in the "test: ITest[]" array, then display it using console.log Challenge: The code is not functioning correctly. What element am I overlooking? Background: I am new to Angular Thank you! Ser ...

Angular2 - Incorporating a New Attribute

I am working with the following Angular2 code: <ngx-datatable-column prop="id" name="ID"> <template ngx-datatable-cell-template let-row="row" let-value="value"> <a [routerLink]="['/devicedtls',r ...

What causes the disparity between Chrome's print preview and printed output? [HTML - CSS]

In my Angular demo project, I have included basic text and a table. There is a print button that calls window.print() to print the page with applied styling. printPage() { window.print(); } CSS: @media print { @page { size: landscap ...

Encountering issues with integrating an external plugin with AngularJS code

For my app, I am attempting to incorporate intercom for monitoring user activity. It functions correctly when placed inside a script tag in index.html. However, I encounter an error when trying to use it in a .ts file as shown below: app/components/rocket/ ...

Issues arise during the migration process of upgrading the project from Angular 8 to Angular 15

I am currently in the process of upgrading an Angular project from version 8.3.26 to a version beyond 12. I know that this should be done incrementally, so my first step is to upgrade to Angular 9. However, when I follow the instructions in the documentati ...

How to access the result without using subscribe in Angular?

I am facing unexpected behavior with a method in my component: private fetchExternalStyleSheet(outerHTML: string): string[] { let externalStyleSheetText: string; let match: RegExpExecArray; const matchedHrefs = []; while (match = this.hrefReg.exe ...

Issue in Typescript: The method `clear` or `send` is not recognized in type `unknown` within Protractor framework

Having trouble using clear and sendKeys in Protractor with TypeScript. Could it be that I am missing certain dependencies, as even the click function is giving errors? I have attempted various solutions from Protractor clear() not working, but unfortunate ...

The error message "Declaration file for module 'mime' not found" was issued when trying to pnpm firebase app

Currently, I am in the process of transitioning from yarn to pnpm within my turborepo monorepo setup. However, I have run into an issue while executing lint or build commands: ../../node_modules/.pnpm/@<a href="/cdn-cgi/l/email-protection" class="__cf_e ...

Create an array variable for services in Angular

My goal is to define this user as an array. users = new BehaviorSubject<any>([]); In my component, I am attempting to add the userID to the array. this.Service.users.push(userID); To subscribe to it, I use the following code: this.Service.users.su ...

Creating a generic class for third-party API requests in NestJS

I'm working on a NestJS application that involves making third-party API requests. Every function requires the same code to retrieve data, causing repetition. How can I streamline this process by creating a common class for handling GET or POST reque ...

Utilizing Sequelize with Typescript for referential integrity constraints

After defining these two Sequelize models: export class Users extends Model<Users> { @HasMany(() => UserRoles) @Column({ primaryKey: true, allowNull: false, unique: true }) UserId: string; @Column({ allowNull: false, unique: tru ...

Having trouble getting Laravel and Angular to filter data by categories?

I am currently developing an ecommerce project using Laravel and Angular. I have products and brands associated with these products. In my function to retrieve the products in Laravel, I have used a nullable parameter like this: public function index($bran ...

The type string[] cannot be assigned to type 'IntrinsicAttributes & string[]'

I'm attempting to pass the prop of todos just like in this codesandbox, but encountering an error: Type '{ todos: string[]; }' is not assignable to type 'IntrinsicAttributes & string[]'. Property 'todos' does not ex ...

How can I populate separate lists with data from an Angular GET request response?

I am new to using Angular and I have been struggling to build a frontend application that can consume my REST API created with Django. Despite searching for two days, I have not found a satisfactory answer to my problem. Chat GPT also seems to be inaccessi ...

retrieve the router information from a location other than the router-outlet

I have set up my layout as shown below. I would like to have my components (each being a separate route) displayed inside mat-card-content. The issue arises when I try to dynamically change mat-card-title, as it is not within the router-outlet and does not ...

Import TypeScript files with RequireJS

I'm looking for some clarification on RequireJS. Right now, I compile all my Typescript files into one JS file. If I switch to RequireJS, does that mean I won't have just one JS file anymore? As I understand it, RequireJS dynamically loads JS f ...

What is the reason behind tsc (Typescript Compiler) disregarding RxJS imports?

I have successfully set up my Angular2 project using JSPM and SystemJS. I am attempting to import RxJS and a few operators in my boot.ts file, but for some reason, my import is not being transpiled into the final boot.js output. // boot.ts import {Observa ...

Occasionally, the translate.get function may return the key instead of the intended

I recently encountered an issue while working on a web application built with Angular 12 and ASP.NET Core 5. The application utilizes ngx-translate for internationalization, but I faced a problem with translating content in a new component that I added to ...

Is TypeScript's Structural Typing the exception to the rule?

Let me illustrate two scenarios where I encountered difficulties. The first example involves two points: one in 2d and one in 3d: type Point2D = { x: number, y: number }; type Point3D = { x: number, y: number, z: number }; let point2D: Point2D = { x: 10, ...

Guide on transferring individual key values from an array to another array sequentially by clicking a button in Angular/JavaScript

I have an array of objects called marrayval. From this array, I want to extract the 'country' values one by one and push them into the arrayval after each click event. For example, on the first click, I would push C1, on the second click C1, C2, ...