简体   繁体   English

强制 MP3 文件充当“另存为...”而不是在浏览器中播放

[英]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.对于包含 mp3 文件列表的页面,我需要为每个具有两个按钮的列表元素构建一个模块:播放和下载按钮。 Clicking the play button, an mp3 player appears which plays audio in the browser as a fixed footer.单击播放按钮,将出现一个 mp3 播放器,它在浏览器中将音频作为固定页脚播放。 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.问题是,即使音频标签包含下载(真正下载)文件的方法,它也会在单击更多(3 个点)按钮后执行。 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) (最后一个属性:type 只是来自我为问题找到的答案,但没有做任何改变)

I've tried everything suggested, but the file still opens a new window and start to play the audio.我已经尝试了所有建议,但该文件仍会打开一个新的 window 并开始播放音频。 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).我正在考虑定义音频标签而不是 a 的第二种方法,在没有控件的情况下定义它,并使用 JS 获取它的下载属性(因为我看到了一种如何拆分功能并构建自定义播放器的方法)。 But I haven't found a way to do it as .play() or .pause() .但我还没有找到一种方法来做.play().pause()

Are there any up-to-date way to force download on an audio file?是否有任何最新的方法可以强制下载音频文件?

Here is a simple snippet to demonstrate using a blob to alter another blob's type.这是一个简单的片段,用于演示使用 blob 更改另一个 blob 的类型。

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.对于这个例子,我使用了一些 HTML,然后将 blob 变成 html / text,然后二进制八进制流进行下载。

 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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM