The object MediaStreamRecorder is not able to be used as a constructor

Just starting my Angular6 journey and I'm experimenting with the MediaStreamRecorder feature. Somehow, I must be messing up the definition of MediaStreamRecorder because all I get is this frustrating error message:

TypeError: msr__WEBPACK_IMPORTED_MODULE_4__.MediaStreamRecorder is not a constructor
. Can someone please point me in the right direction on how to properly declare and define MediaStreamRecorder? Any help would be greatly appreciated!

To give you some context, I have added the msr module to my project, and here's a snippet of my code:

import { Component,ViewChild, OnInit, Inject } from '@angular/core';
import { LinksService } from 'demo/_services/links.service';
import { Http,Response,Headers } from '@angular/http';
import { MediaStreamRecorder} from 'msr';
import { RecordRTC } from 'recordrtc';

@Component({
  selector: 'demo-ceva',
  templateUrl: './ceva.component.html',
  styleUrls: ['./ceva.component.css'],
  providers: [
    {
      provide: SpeechRecognitionLang,
      useValue: 'en-US',
    },    
    SpeechRecognitionService,
  ],
})
export class CevaComponent { 
  public navigator: any;      
  public MediaStreamRecorder: any;    
  constructor( private http: Http, private service: SpeechRecognitionService, private links: LinksService ) { 
this.record = () => {       
    var browser = <any>navigator;  
    var obj = { audio: true, video:false };
    browser.getUserMedia = (browser.getUserMedia || browser.webkitGetUserMedia || browser.mozGetUserMedia || browser.msGetUserMedia);     
    browser.mediaDevices.getUserMedia(obj).then(stream => {  
        var source = window.URL.createObjectURL(stream);      
        var config= { ... }  
        var recorder = new MediaStreamRecorder(stream, config);
        recorder.record();
        recorder.stop(function(blob) {     
            var blob = recorder.blob;
            console.log(blob);           
        });
   });
});

Answer №1

After following the advice given in this thread, I found the solution to my issue was to make specific declarations in the typings.d.ts file:

declare interface MediaRecorderErrorEvent extends Event {
  name: string;
}

declare interface MediaRecorderDataAvailableEvent extends Event {
  data : any;
}

interface MediaRecorderEventMap {
  'dataavailable': MediaRecorderDataAvailableEvent;
  'error': MediaRecorderErrorEvent ;
  'pause': Event;
  'resume': Event;
  'start': Event;
  'stop': Event;
  'warning': MediaRecorderErrorEvent ;
}


declare class MediaRecorder extends EventTarget {

  readonly mimeType: string;
  // readonly MimeType: 'audio/wav';
  readonly state: 'inactive' | 'recording' | 'paused';
  readonly stream: MediaStream;
  ignoreMutedMedia: boolean;
  videoBitsPerSecond: number;
  audioBitsPerSecond: number;

  ondataavailable: (event : MediaRecorderDataAvailableEvent) => void;
  onerror: (event: MediaRecorderErrorEvent) => void;
  onpause: () => void;
  onresume: () => void;
  onstart: () => void;
  onstop: () => void;

  constructor(stream: MediaStream);

  start();

  stop();

  resume();

  pause();

  isTypeSupported(type: string): boolean;

  requestData();


  addEventListener<K extends keyof MediaRecorderEventMap>(type: K, listener: (this: MediaStream, ev: MediaRecorderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;

  addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;

  removeEventListener<K extends keyof MediaRecorderEventMap>(type: K, listener: (this: MediaStream, ev: MediaRecorderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;

  removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;

By implementing these declarations, I was able to instantiate a new MediaRecorder object in my component simply with

var mediaRecorder = new MediaRecorder(stream);
. Much appreciation to @firegloves for sharing the link that led me here and thank you, @Tiberiu C., for providing the answer. It made a significant difference.

Answer №2

Run the command `npm install -D @types/dom-mediacapture-record` to add the necessary types for DOM Media Capture Record.

Answer №3

Encountering a similar problem in my experience with using pure JS and React, I found that the issue was resolved by removing the line below:

window.MediaRecorder = require('audio-recorder-polyfill');

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

Activate a function to focus on an input field once ngIf condition becomes true and the input is revealed

I am currently attempting to focus the cursor on a specific input field that is only displayed when the condition of the surrounding ngIf directive is true. Here is an example of the HTML code structure: <div> <button (click)="showFirst = ...

The import map is not being recognized by Supabase Edge Functions when passed in the command `npx supabase functions serve`

My situation involves two edge functions, namely create-payment-link and retrieve-payment-link. However, they are currently utilizing the import map located at /home/deno/flag_import_map.json, rather than the import_map.json file within the functions folde ...

Unable to Reopen Bootstrap Modal Using Key After Closure

Presently, I have this code in place for a Twitter Bootstrap modal: <!-- Button trigger modal --> <button type="button" class="btn btn-success btn-lg btn-block" id="confirm" data-toggle="modal" data-target="#myModal" style="margin: auto; ...

What are the best tools to develop a browser-based 2D top-down soccer simulation?

I'm looking to create a 2D top-down soccer simulation game for web browsers using modern technologies and without the need for additional plugins like Flash or Silverlight, making it compatible with mobile devices as well. The game will be AI-controll ...

Utilizing Mongoose's Nested Arrays with ObjectId

I am currently working on a functionality to track the IDs of the posts that users have voted on. For this, I have devised a schema as shown below: var userSchema = new Schema({ twittername: String, twitterID: Number, votedPosts: [{ObjectId : ...

Retrieving information from subscription

I am currently diving into Angular 2 and have successfully fetched data from my service. However, before displaying it on the view, I need to iterate over it using a for() loop. To achieve this, I have stored the fetched JSON data into an array. But I&apos ...

Passing conditional empty variables through `res.render`

I am currently facing a challenge with passing multiple variables into a res.render. One of the variables will have an object to send through, while the other may not have anything to pass. As a result, I am encountering an undefined error. Below is the ...

The swipe motion will be executed two times

By pressing the Circle button, the Box will shift to the right and vanish from view. Further details (FW/tool version, etc.) react scss Typescript framer-motion import "./style.scss"; import React, { FunctionComponent, useState } from &q ...

Exploring the world of jQuery and Ajax to retrieve a full HTML framework

I'm a beginner in jQuery and JavaScript programming. While I've managed to use jQuery for my Ajax calls, I'm facing an issue that has me stumped. When making an Ajax call, I'm trying to return a complete HTML structure, specifically a ...

What steps can I take to allow a third-party JavaScript to access my TypeScript object?

I am working on an Angular application and I have a requirement to develop an API for a third-party JavaScript that will be injected dynamically. public class MyApi{ public callSomeFunction():void{...} public getSomeValue():any {...} } var publicA ...

Sliding off the canvas - concealed navigation

I have implemented CSS to hide a menu on mobile: #filter-column { position:absolute; left:-400px; } However, I want the menu to slide in from the left when the user clicks a link, and everything else should be hidden. When the layer is closed, th ...

Angular Kendo UI offers the ability to customize the way grid columns are sorted

I'm currently working on a Kendo Grid (UI for Jquery) where I have implemented a custom sort method for a specific column based on my customers' requirements. field: "daysLeft", title: "Accessible", width: 130, sortable: { compare: function (a ...

Ways to identify local storage when a user visits the page for the first time using jQuery

As a beginner in the world of local storage in Jquery, I am looking to implement a feature on my Bootstrap 4 accordion. The desired functionality is as follows: If a user is visiting the page for the first time, all accordions should be open by default ...

Is the runTest.ts class in the vscode-test setup ever utilized in the project? Its purpose remains unclear even in the example project

Being a novice to Typescript, JavaScript, and VScode Extensions I have set up a vscode-test following the guidelines provided here: https://code.visualstudio.com/api/working-with-extensions/testing-extension#custom-setup-with-vscodetest Based on the hel ...

Create individual account pages with specific URLs in Next.js

I'm currently working on developing a website that will feature individual user pages showcasing their posts and additional information. I'm facing some difficulty in figuring out how to generate new links to access these user accounts. For insta ...

What is the process for receiving notifications from Stack Overflow for new questions?

Interested in responding to the latest questions on JavaScript, React, React Native and Node.js. How can I stay updated on new user queries related to these topics? ...

When attempting to create a generic key value interface, Typescript will throw an error if a mapped type is used that declares properties or methods

I am attempting to design an interface that can accept generic key-value pairs in the following format export interface GetModel<K extends string, T> { [key in K]: T; } However, I encountered this error message A mapped type may not declare prop ...

Tips on modifying the font color of specific text using javascript

I'm facing an issue in my JavaScript code where I need to change the background color of some text. Currently, I am able to print a coupon on white paper which is working fine. For example: Here is how the output receipt will look like ************* ...

Guide on how to streamline JSON output from aggregation result

I have written a NodeJs api using mongo db aggregation to obtain some output. However, the result I received is not what I expected. Can anyone help me figure out how to get the desired output? app.get('/polute', function (req, res) { Light. ...

PHP fails to retrieve data from a JavaScript Ajax function using the FormData object (specifically, when

I'm facing an issue where my file is not being detected when I send a FormData object using AJAX and PHP code. Both the `$_FILES` array and the `$_POST` array appear to be empty. However, the browser does send the file with the AJAX request. <inpu ...