get and enjoy streaming audio in Angular 8

Currently, I am facing an issue where I want the audio to play when the user clicks on the preview icon. Here is the HTML code:

<audio controls>
    <source [src]="fileSource" type="audio/mp3">
</audio>

This is my TypeScript code:

fileSource: any;

ngOnInit(): void {
if (typeof this.data.src === 'number') {
  this.getImageFromService();
  }
}

createImageFromBlob(image: Blob): void {
const reader = new FileReader();
reader.addEventListener('load', () => {
this.fileSource = reader.result;
}, false);

if (image) {
reader.readAsDataURL(image);
}
}

getImageFromService(): void {

this.isLoading = true;
this.postFileService.downloadFile(this.data.src).subscribe(data => {
this.createImageFromBlob(data);
this.isLoading = false;
}, error => {
this.isLoading = false;
console.log(error);
});
}

And here is my service:

downloadFile(id: number): Observable<Blob> {
const URL = `${this.appConfig.apiEndpoint + '/PostFileContent/DownloadFile/' + id}`;

return this.http.get(URL, { responseType: 'blob' });
}

My current problem is that when I click on the preview icon, the file is downloaded but it does not play. What could be causing this issue? How can I resolve it?

Answer №1

To automatically play an audio file retrieved from a backend (node.js), use the following code.

index.html

<audio controls>
  <source type="audio/mpeg" [src]="fileSource">
</audio>

script.js

// Specify your backend URL directly below
fileSource:any = 'http://localhost:1234/getAudioFile';

node-server.js

app.use('/getAudioFile', function(req, res, next){
  // Sample mp3 file stored locally
  var filePath = path1.join(__dirname, './sample.mp3');
  var stat = fileSystem.statSync(filePath);

  res.writeHead(200, {
    'Content-Type': 'audio/mpeg',
    'Content-Length': stat.size
  });

  var readStream = fileSystem.createReadStream(filePath);
  
  // Simplified streaming with readStream.pipe()
  readStream.pipe(res);
  next();
});

Note:: Ensure direct retrieval of audio files from the backend (regardless of node or java).

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

JavaScript Question: How can I extract the click value from a JavaScript visualization when displayed in a table?

I am working with a Hierarchical Edge Bundling visualization in JS. My goal is to have the name of the value displayed on the table when I click on it. Currently, I am facing an issue with retrieving the value dynamically. If I manually input a value, I c ...

Invoke a specific script snippet by its identifier within a React single-page application, causing the content to appear only upon manual

I am currently working on a React application that utilizes a third-party JS script from OneTrust cookie scripts. Unfortunately, the scripts provided are not optimized for single-page applications (SPAs). At the moment, I am simply referencing the script s ...

Can a post request be sent in Node/Express using just HTML and server-side JavaScript (Node.js)?

Can a post request be made in Node/Express using only HTML and Server-side Javascript? (HTML) <form action="/submit-test" method="post"> <input type="text" name="id"> <button type="submit">Submit</button> </form> (N ...

Mobile users experiencing crashes when interacting with an Iframe containing Three.js on the webpage

One of the challenges I'm facing is with a modal that contains an Iframe utilizing Three.js to load a 3D Door. While this setup works smoothly on desktop, it encounters issues on mobile devices. When interacting with the Iframe on mobile, it either cr ...

Adjust the position of elements to prevent overlap

I'm facing a problem with elements overlapping on my website. The navbar is sticky, meaning it slides down the page when scrolling. Additionally, I have a "to-top" button that automatically takes you to the header when clicked. I want the "to-top" but ...

Automated Submission and Online Posting of (Web Form) with JavaScript Script

Is there a way to automatically fill out the form on my webpage ( ) using a JavaScript function with specific parameters? The source code for the webpage can be found here: webpage sourcecode script enter image description here ...

Using a carousel component in Bootstrap

Just starting out with this, trying to customize Bootstrap to change slides automatically. I followed the documentation at https://getbootstrap.com/docs/4.3/components/carousel/ but for some reason, the slides aren't changing on an interval, even thou ...

Creating crawlable AMP versions of Angular websites

Having an Angular website where I dynamically load object properties, I am creating separate AMP sites for each of these objects. Typically, I would link to the AMP site from the canonical site. However, the issue arises because the crawler cannot find the ...

Issues with JQuery Ajax file upload functionality in the client's browser causing upload problems

Seeking to integrate a profile picture upload feature with Ajax and JQuery I've been successful in uploading profile pictures to my database on various machines and mobile devices, including Chrome, Edge, Firefox, Safari, and Vivaldi. However, my cl ...

The backend function of an aspx page is failing to execute when triggered by a $.ajax request

Currently, I am facing an issue with a web form IndexPage.aspx. The script in this front-end code makes an ajax call to a code-behind function. Take a look at the code snippet below: $.ajax({ type: "POST", url: &apos ...

Tips for making a oneOf field nullable using TypeScript and AJV

A field named platform exists in my code, and it can hold either a string or an array of strings (string[]). The field can also be nullable or undefined if not passed as input. TypeScript Interface export interface IEntityLeaderboardQuery { rank: stri ...

gmap3 has encountered an error: undefined is not a valid function

I am working on a WordPress site and trying to integrate a Google map into the contact page. However, I'm encountering an error Uncaught TypeError: undefined is not a function in the JavaScript console. Below is the code snippet causing the issue, can ...

How can I store a value or text to track view counts or a counter efficiently?

Recently, I've been trying to implement a view counter on my website, similar to what you see on YouTube. Currently, the number of views stands at 23. I managed to find some code that allows me to increment the view count every time I click on an imag ...

Syntax error is not caught - why are there invalid regular expression flags being used?

I'm attempting to dynamically create rows that, when clicked, load a view for the associated row. Check out my javascript and jquery code below: var newRow = $('<tr />'); var url = '@Url.Action("Get", "myController", new ...

Move the image inside the box without directly following the mouse cursor, but at a slightly faster pace

I am facing an issue with a Vue component that allows me to zoom in on an image and move it around the container. The problem is, when the image is zoomed in, it moves faster than the mouse due to using the scale transform. Additionally, I noticed that cl ...

Is there a point in bundling NPM packages if they are ultimately going to be bundled by the project

I'm in the process of creating a TypeScript package for publication on NPM. My plan is to utilize this package in upcoming web development endeavors, most likely utilizing Vite. As I look ahead to constructing a future website with this module, I am c ...

Updating Span or Div content by ID using Jquery and Ajax without needing to reload the page

Here is the code snippet I am working with: <span class='numberofthings' id='123456'> Things: ".$things."</span> Along with the following JavaScript / Ajax code: function click(obj) { $.ajax({ var id = 123456 ...

Is JavaScript necessary for this task in PHP?

Hi everyone, I recently discovered a way to style a PHP echo in a more visually appealing manner. Instead of presenting an unattractive colored box right away, I was wondering if there is a way to only display the box when the user selects the calculation ...

Exclude promises from a type in TypeScript

Here is my TypeScript snippet: async function get_string(){ return "hello" } var the_string = get_string() In the code, the type of the_string is Promise<string> I am interested in removing the Promise from the type of the_string and m ...

Tips for customizing the legend color in Angular-chart.js

In the angular-chart.js documentation, there is a pie/polar chart example with a colored legend in the very last section. While this seems like the solution I need, I encountered an issue: My frontend code mirrors the code from the documentation: <can ...