Gergő Horváth
Gergő Horváth

Reputation: 3705

Force MP3 file to act as "Save as..." instead of playing in the browser

For a page which contains a list of mp3 files, I need to build a module for each listelement which has two button: a play and a download button. Clicking the play button, an mp3 player appears which plays audio in the browser as a fixed footer. I also need to provide a simple way for the user to download the file. The problem is that even if the audio tag contains a way to download (really download) the file, it does after clicking the more (3 dots) button. This is not what I want. I need to provide a direct download functionality for the download button. I started with the simplest approach:

//jsx
<a
    target="_blank"
    href={file.source}
    download={file.name}
    className="download-button"
    type="application/octet-stream"
/>

(the last attribute: type is just from an answer I found for the problem, but doesn't make any change)

I've tried everything suggested, but the file still opens a new window and start to play the audio. The download attribute seems no longer working.

The second approach I was thinking of to define an audio tag istead of the a, define it without controls, and with JS, get the download attribute of it (as I saw a way how to split the features and build a custom player). But I haven't found a way to do it as .play() or .pause().

Are there any up-to-date way to force download on an audio file?

Upvotes: 0

Views: 1770

Answers (1)

Keith
Keith

Reputation: 24191

Here is a simple snippet to demonstrate using a blob to alter another blob's type.

For this is example I've use some HTML, and then make the blob into a html / text and then binary octect-stream for downloading.

const encoder = new TextEncoder();
const data = encoder.encode('This is <b>bold</b>');

function createLink(name, type) {
  const a = document.createElement("a");
  a.innerText = name;
  document.body.appendChild(a);
  document.body.appendChild(document.createElement('br'));
  const blob = new Blob([data], {type})
  const url = URL.createObjectURL(blob);
  a.setAttribute('href', url); 
}

createLink('HTML download', 'text/html');
createLink('TEXT download', 'text/plain');
createLink('Binary download', 'application/octet-stream');

Upvotes: 1

Related Questions