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

What is the best way to iterate through an array within a class in Angular 2?

I am trying to iterate over an array named data, within another array containing 'champions'. Can anyone provide the correct syntax for this? I can successfully loop through all the champions within my IChampion interface, but I'm having tro ...

Bundling and minifying Angular2 assets

In the world of ASP.NET (or gulp), bundling and minification are taken care of. However, a different issue arises when following Angular2 tutorials: the view HTML is typically embedded within the component itself. Fortunately, there is a way to separate th ...

What is a more precise way to define an Object type on a temporary basis?

I'm currently working with Angular 2. Typically, when I specify a type, I start by creating an interface: interface Product { name: string, count: number } and then use it like this: let product: Product; However, now I need to temporarily de ...

Tips for developing a collaborative service for utilization across numerous Angular applications

Is it feasible to develop a shared service that can be utilized in numerous Angular applications? And if so, how? For instance, similar to how we create an Angular library that can be accessed externally by packaging it into an npm package. Is it possible ...

Is it possible to run Angular2 and Expressjs on separate ports?

I have set up my Angular2 application to use Expressjs as the backend. Both projects are structured within the same directory: /index.html <-- Angular index file /app.js <-- Expressjs /package.json /Gruntfile.js /bin <-- Expressjs bin ...

Error: Unable to access the 'registerControl' property of the object due to a type mismatch

I'm struggling to set up new password and confirm password validation in Angular 4. As a novice in Angular, I've attempted various approaches but keep encountering the same error. Seeking guidance on where my mistake lies. Any help in resolving t ...

What sets my project apart from the rest that makes TypeScript definition files unnecessary?

Utilizing .js libraries in my .ts project works seamlessly, with no issues arising. I have not utilized any *.d.ts files in my project at all. Could someone please explain how this functionality is achievable? ...

You won't find the property 'includes' on a type of 'string[]' even if you're using ES7 features

I encountered a similar issue on another page where it was suggested to modify the lib in tsconfig.josn. However, even after changing compile to es7, the same error kept appearing and the project couldn't be compiled or built. { "compileOnSave": ...

The system is unable to locate the module at 'C:UsersSanjaiAppDataRoaming pm ode_modulesprotractorinprotractor'. This error originates from internal/modules/cjs/loader.js at line 960

After running "protractor conf.js" without any issues, I decided to install protractor globally using the command "npm install -g protractor". However, after installing protractor globally, I encountered the following error message: internal/modules/cjs/lo ...

Issue with Vue @Watch not properly recognizing changes in a boolean value

I'm currently experimenting with watch functions in vue-ts. I have configured a watch function that is supposed to trigger whenever a Boolean variable's value changes, but for some reason, it's not triggering at all and I'm unable to de ...

Leveraging Multiple @Input Decorators in Ionic 3 and Angular 2

Within my Ionic 3 project, I have developed a custom component called my-component. Utilizing the angular @Input functionality, data can be passed to this component with ease. In this case, I have two inputs defined as: @Input('finder') myFinder ...

What is the proper method for typing unidentified exports that are to be used in TypeScript through named imports?

Currently, I am developing an NPM package that takes the process.env, transforms it, and then exports the transformed environment for easier usage. The module is structured like this: const transformedEnv = transform(process.env) module.exports = transf ...

The click event fails to provide $event upon being clicked

Within my HTML structure in an angular 7 application, I have the following setup: My goal is to trigger the GetContent() function when any text inside the div is clicked. Strangely, when clicking on the actual text, $event captures "Liquidity" correctly. ...

Tips for resolving the issue of dropdown menus not closing when clicking outside of them

I am currently working on an angular 5 project where the homepage consists of several components. One of the components, navbarComponent, includes a dropdown list feature. I want this dropdown list to automatically close when clicked outside of it. Here i ...

Update the component following an HTTP post request

I have an addProjectModal component that allows users to add new projects. save(data:Project) { data.customer_id = this.customerID; data.supervisor_id = 450; this._projectService.addProject(data) .subscribe(res => console.log(res)); //initiat ...

Automatic type inference for TypeScript getters

It appears that Typescript infers field types based solely on the private variable of a field, rather than taking into account the getter's return type union (1) or inferring from the getter itself (2): test('field type inference', () =& ...

Combining RxJS Observables through interval operations

Hey everyone, I have a question for the community! Currently, I am developing an app that communicates with an API in the following manner: Step 1: Create request options and add request payload --> Send a POST request to the API The API responds with a ...

Using `it` with accessing class members

When testing whether a specific object/class is correctly wired up, I often utilize it.each to prevent writing repetitive tests. The issue arises when the type of the object doesn't have an index signature, requiring me to cast it to any for it to fun ...

Ways to boost performance in an Angular 6.0 application

https://i.stack.imgur.com/Rq9Y2.jpg We have recently developed a cutting-edge application using Angular 6, hosted on an Apache 2.4 server. To ensure our website is properly crawled by search engines, we set up a local "prerender" instance. Initially, we t ...

Tips for retrieving an object from an array with Angular and Firestore

Currently, I am attempting to retrieve an object from Firestore using the uid so that I can return a specific object as a value. I have implemented a function in order to obtain the object 'Banana'. getFruit(fruitUid: string, basketUid: string) ...