Experience the convenience of streaming MP3 files directly through the HTML5 audio tag, eliminating the need

Within the function document.ready, I have included the following code snippet:

audioElement = document.createElement('audio');

audioElement.setAttribute('src', 'http://www.mfiles.co.uk/mp3-downloads/Toccata-and-Fugue-Dm.mp3');

$('#ToggleStart').click(function () {
    audioElement.play();
});

$('#ToggleStop').click(function () {
    audioElement.pause();
});

An issue arises as the MP3 file is downloaded when the page loads, resulting in a prolonged load time due to its size of over 2MB. My objective is to stream the MP3 instead. Is there a way to achieve this, and if so, what modifications are required?

Access the corresponding jsFiddle webpage here.

Answer №1

Seems like you're on the right track. After reviewing your JSFiddle, I noticed that the audio is already streaming (you can play the file before it finishes downloading). To confirm this, simply check the Network traffic in your browser:

Chrome indicates 'partial content,' while playing the mp3 concurrently. Your issue appears to be related to downloading and playing too early. Referring to the specifications, there are some options available.

preload = "none" or "metadata" or "auto" or "" (empty string) or empty
This attribute provides a hint to the browser regarding whether optimistic downloading of the audio stream itself or its metadata is worthwhile.
- "none": Indicates to the browser that the user may not require the audio stream, or minimizing unnecessary traffic is preferred.
- "metadata": Suggests to the browser that the user may not need the audio stream but fetching its metadata (duration, etc.) is desirable.
- "auto": Indicates to the browser that optimistically downloading the entire audio stream is preferable.

As you aren't displaying any information about the audio file, we can disregard the metadata option. Therefore, you should set the preload="none" attribute. By dynamically setting this in your JSFiddle like so:

audioElement.setAttribute('preload', "none");
audioElement.setAttribute('src', 'http://www.mfiles.co.uk/mp3-downloads/Toccata-and-Fugue-Dm.mp3');

Check out this JSFiddle for the modified version. If you open the network tab in Chrome, you'll notice that the download only starts when you begin playing the mp3.

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

AngularJS provides users with the ability to access additional information by matching specific identification

Is there a simple way in Angular to display the label of an item from an array without looping through it? I have an array of color options: $scope.colors=[ {id:"0",label:"blue"}, {id:"1",label:"red"}, {id:"2",label:"green"} ] And my data object store ...

Unable to display image on React page using relative file path from JSON data

Greetings, this is my initial post so please forgive me if I have missed any important information. I'm currently in the process of creating a webpage using react. My goal is to display content on the page by iterating over a relatively straightforwa ...

Adding pictures to Cloudinary

My goal is to upload files directly to Cloudinary using nodejs. I have managed to achieve success when I manually set the path of the image I am uploading, as shown below: cloudinary.uploader.upload('./public/css/img/' + data.image) However, whe ...

Detect the size changes of a React DOM node using hooks

Is it possible to measure a React DOM node during the window resize event? I followed the example provided in the React hooks-faq, but it seems to only work for the initial render. When I tried adding a useEffect to listen for the resize event, the callb ...

What are the advantages of using the fat arrow instead of straight assignment?

Here we have a code snippet sourced from the 30 seconds of code website. This example, intended for beginners, has left me feeling stumped. The question arises: const currentURL = () => window.location.href; Why complicate things when you could just ...

Guide to incorporating an input field within a select option in ant design and react

I have utilized Ant Design to create a select option, but now I am looking to implement an editable cell within the select option. Below is the code for my select option: <Select showSearch style={{ width: 400 }} placeholder="Select a Bank" op ...

Generating rows within Angular while implementing ng-repeat

In my code, I am facing an issue where posts from the API are being repeated and displayed in rows of 9. My objective is to create a grid layout with 3 rows, each containing 3 posts. Unfortunately, the solution I attempted did not work as expected. I also ...

Unable to insert a JSON object into an Array

This might appear to be a duplicate, but it's not. None of the solutions I've tried have worked. Within my angular module, I have a list: this.checkedInterviews = [] Followed by a function that does the following: var interviewModel = { ...

Why is Socket.io functioning on localhost but fails to work once deployed to Heroku?

Sharing my socket server code: const io = require("socket.io")(8080, { cors: { // origin: "http://localhost:3000", origin: "https://mern-bubble.herokuapp.com", }, }); This is the client-side implementation: useEf ...

Upon concatenation, the screen automatically returns to the beginning of the page

I've set up a page with a list of items, and at the bottom there's a handy "Load more" button that fetches new items to add on top of the existing list: handleLoadProducts = (append = false) => { this.setState({ isLoading: true, ...

Recalling the use of jquery toggle throughout the website?

I have successfully implemented a button to hide and unhide a lengthy menu with a click, but I am struggling to make the menu state persistent across multiple pages. I would like the last toggle action by the visitor to be remembered. Any suggestions on ho ...

The argument labeled as 'State' cannot be assigned to a parameter labeled as 'never'

I've recently delved into using TypeScript with React. I attempted to incorporate it with the React useReducer hook, but I hit a roadblock due to an unusual error. Below is my code snippet: export interface ContractObj { company: string; ...

What is the best way to utilize the Rails Rest in Peace gem within an iteration loop?

I've implemented the Rest in Place gem from https://github.com/janv/rest_in_place. Could you guide me on how to properly use it within an each loop, specifically for a belongs_to relationship? For instance, assume User has_many :fee_agreements, and ...

The functionality is not operating correctly on Internet Explorer

This code is functioning properly in Mozilla and Opera, but it is not working in IE. Any assistance on this issue would be greatly appreciated. The JavaScript is working fine, however, in IE 10 only the back panel is displayed. Thank you for your help. h ...

Position the cursor at the conclusion of a text input box and ensure that the conclusion is in view

I feel like I'm losing my mind. The autosuggest box on my website is causing some issues. When users select a suggestion, the text input box's value exceeds its size upon the next selection. Although I can move the carat to the end of the input f ...

Tips for updating the version number in a non-integer JSON format

Every time I run this code, I want it to update the JSON file. The problem: 1. The version in the JSON file is stored as a string rather than an integer Solution: I plan to extract the version number, convert it to an integer by removing the periods, ...

Parcel-Bundler is unable to resolve critical security issues

I recently followed a tutorial by Kevin Powell on SASS and Parcel through YouTube. I was able to successfully set up the SASS part and get the Parcel bundler working smoothly on one project, so everything seemed to be going well at that point. However, to ...

Steps to retrieve values from a grid and execute a sum operation using PROTRACTOR

Embarking on my Protractor and Javascript journey, I am faced with the challenge of writing a test script to retrieve values of various accounts under the header "Revenue" (as shown in the image below). My task involves extracting all number values listed ...

Guidelines for creating an auto-scrolling React Native FlatList similar to a Marquee

I currently have a FlatList component set up in my project. <FlatList horizontal data={data} key={(item, index) => index.toString()} ListHeaderComponent={listHeader} renderItem={ // renderin ...

Comparing a stored array in Mongo against a native JavaScript array with identical length and values results in a failed deep assert comparison

In my mongoose ORM, I have a field in mongo defined as: state: {type: [Number], required: true } When I check a sample document in the mongo console, the state appears as: state: [ 1, 1, 1 ] Everything seems to be in order so far. However, when I try t ...