Capturing HLS audio stream with MediaRecorder in typescript

Currently, I am trying to manipulate a HLS audio feed that is set as the source for an audio player element. My goal is to record this incoming stream for future use. Despite using the MediaRecorder package to capture the stream from the audio player source, I have encountered a roadblock where the media recorder indicates that the source is not of type 'MediaStream'.

Here is the code snippet for initializing the stream to be played in the audio element:

  initStream() {
    // get the audio player
    let audioEl = this.audioPlayer.nativeElement;

    // create the HLS object
    this.hls = new Hls();

    // stream source URL
    var source = "https://as-hls-uk-live.akamaized.net/pool_904/live/uk/bbc_radio_one/bbc_radio_one.isml/bbc_radio_one-audio%3d128000.norewind.m3u8";

    // assign the source to the HLS object
    this.hls.loadSource(source);

    //attach the HLS to the audio player
    this.hls.attachMedia(audioEl);

    console.log(`Created audioPlayer${this.playerId}`);
  }

This is followed by the code for initializing the stream recording:

initRecording(){
    this.recorder = null;
    this.recordedChunks = [];
    try {
      this.recorder = new MediaRecorder(this.hls, {mimeType: "audio/ogg"});
    } catch (e) {
      console.error('Exception while creating MediaRecorder: ' + e);
      return;
    }
    this.recorder.ondataavailable = (event) => {
      console.log(' Recorded chunk of size ' + event.data.size + "B");
      this.recordedChunks.push(event.data);
    };

    this.recorder.start();
  }

Unfortunately, when attempting to initialize the recording, I receive the following error message:

Exception while creating MediaRecorder: TypeError: Failed to construct 'MediaRecorder': parameter 1 is not of type 'MediaStream'
. It seems like passing the HLS object into the media recorder is causing this issue. Is there an alternative attribute within that object that could work instead?

I also attempted to use the audio player source as the stream input for the media recorder. However, in this scenario, the media recorder fails to start recording due to no tracks being listed in the source.

initRecording(){
    let audioEl = this.audioPlayer.nativeElement;
    var audioStream = audioEl.src;
    this.recorder = null;
    this.recordedChunks = [];
    try {
      this.recorder = new MediaRecorder(audioStream, {mimeType: "audio/ogg"});
    } catch (e) {
      console.error('Exception while creating MediaRecorder: ' + e);
      return;
    }
    this.recorder.ondataavailable = (event) => {
      console.log(' Recorded chunk of size ' + event.data.size + "B");
      this.recordedChunks.push(event.data);
    };

    this.recorder.start();
  }

Answer №1

To properly record audio, you must utilize a 'MediaStream' type. Generate one by implementing the captureStream method on your audio HTML media element and then feed it into your MediaRecorder

const recordedAudio = audioElement.captureStream()

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 modify the color of a table cell in Typescript with *ngFor loop?

I have an image located at the following link: https://i.sstatic.net/rxDQT.png My goal is to have cells with different colors, where main action=1 results in a green cell and action=0 results in a red cell. Below is the HTML code I am working with: & ...

What is the process for incorporating a personalized inputComponent JSX <input /> into a react-phone-number-input PhoneInput component?

Instructions to follow when working with code. react-phone-number-input provides the option for users to replace its default <input /> JSX tag with a custom one, requiring the type React.ForwardRefExoticComponent<React.InputHTMLAttributes<HTML ...

When using React.useReducer(), an error TS2769 is thrown indicating that no overload matches the function call

Recently started using TS. I created a basic demo app that utilizes the useReducer() hook to handle the selected state of items in a list. I believed I had implemented type safety in the reducer, but upon calling the useReducer() hook, I encountered the TS ...

The Angular material slider experiences issues with functionality when paired with the *ngFor directive

Having a unique problem that I could easily replicate on stackblitz. When using multiple mat sliders generated from a *ngFor loop with numbers as values, encountering an issue where moving the first slider affects all others. Subsequent drags only update ...

Working with Angular 4: Utilizing HttpResponse in a Component

I am attempting to retrieve the response from my POST request using Angular 4. Below is the code I am using: app.component.html: `findAccordiSmall(pagination: Pagination) { this.accordiListTableLoading = true; debugger; this.ac ...

Extracting data from a JSON object using Angular 2

I need advice on the most efficient way to handle JSON within my angular2 application. The JSON data I am working with includes: { "rightUpperLogoId": { "id": 100000, "value": "" }, "navbarBackgroundColorIdCss": { "id" ...

Ensure that the Observable is properly declared for the item list

.html // based on the error message, the issue seems to be in the HTML code <ion-card *ngFor="let invitedEvent of invitedEvents"> <ion-card-content> <img [src]="eventPhotoUrl$[invitedEvent.id] | async"> </ion ...

Guide to converting a string into an undefined type

I've been working on parsing a csv file: let lines = csvData.split(/\r\n|\n/); let headers = lines[0].split(','); for (let i = 1; i < lines.length; i++) { let values = lines[i].split(','); ...

Error: Visual Studio unable to locate Firebase node module

After running the command npm install firebase --save in the root of my project folder, a firebase folder was successfully added to my node_modules directory and the packages.json file was updated accordingly. In addition to using typescript, I have an ap ...

Creating Versatile Functions for HttpClient Wrapping

Scenario: In my set of services, I find myself repeatedly writing code for data calls which results in a lot of duplicated code. To streamline the process and reduce redundancy, I am looking to implement a wrapper function: All these functions essentiall ...

How can one retrieve the "code" attribute from a FirebaseError object in AngularFire using TypeScript?

When using FirebaseError with a "code" property, how can you access it within the catch method of a promise? The code snippet below results in a TypeScript error: Property 'code' does not exist on type 'Error'. this.af.database .object ...

Angular 2: Issue with Component not reinitializing when query parameters change

I am currently working with Angular 2 and the latest router component to create a search functionality. Upon clicking the search button for the first time, the router navigates to the search component and retrieves data from the service. However, I have no ...

The Typescript counterpart to PropTypes.oneOf, utilizing a pre-existing variable

While I know this question has been addressed on Stack Overflow here, I still find myself struggling with a similar issue in my TypeScript project. Currently, I am in the process of converting a JavaScript project to Typescript. Within one of my React com ...

What prevents the right side of this conditional type from being defined as never?

During type-checking time, I have a rule to enforce regarding the parameters that can be passed to my function. The type is described in the following code snippet: type CheckConf<TConf extends SupportedConf> = { [Key in keyof TConf]: TConf[Key] e ...

Switch the value to a public object on Google's autocomplete feature

I have a public object called location, and when the callback is executed, I need to assign values to that object.... public location: any; ngOnInit() { let autocomplete = new google.maps.places.Autocomplete((this.search.nativeElement), {types: [ ...

Developing a declaration for an unnamed function in a JavaScript file

module.exports = function (argument1, argument2) { return { myFunction } function myFunction () { ... } } What is the process for creating a TypeScript declaration file for this specific JavaScript file? ...

What is the correct way to implement Vue.use() with TypeScript?

I am trying to incorporate the Vuetify plugin into my TypeScript project. The documentation (available at this link) suggests using Vue.use(), but in TypeScript, I encounter the following error: "error TS2345: Argument of type '{}' is not assign ...

Change the type of an object to a different type

Within my class, I have set the type of range to IntervalRange. export class Test {range: IntervalRange;} Then, in the parent class, I initialize the value: export class TestInitializer { Create(){ return <Test>{ range: IntervalRange.i ...

Show all span elements in a map except for the last one

Within my ReactJS application, I have implemented a mapping function to iterate through an Object. In between each element generated from the mapping process, I am including a span containing a simple care symbol. The following code snippet demonstrates t ...

Conditional property determined by the value of an enumeration

Trying to implement type checking for a react useReducer. I have an action where the existence of an optional property (data) depends on the value of another property. If STATUS is set to VIEW or EDIT, then the action must include the data property. Altho ...