使用javascript函数从html下载音频文件
我试图通过单击按钮来下载 mp3 文件,它会下载,但它下载的文件不正确,它比原始文件(25 字节)小得多,而原始文件为 10MB。
这是我第一次下载东西,所以我很无能。
下面是一些代码:
JS 函数:
function download(i) {
var audio = document.getElementById("audio"+i);
const blob = new Blob([audio], {type:"octet-steam"});
const href = URL.createObjectURL(blob);
const a = Object.assign(document.createElement("a"), {
href,
style: "display:none",
download: "myAudio.mp3",
});
document.body.appendChild(a);
a.click();
URL.revokeObjectURL(href);
a.remove();
}
音频通过其 ID 进行标识,其文件名来自我在数据库中的数据。 HTML/PHP
for($i=0; $i<$count; $i++){
$res = mysqli_fetch_array($result);
echo('<tbody id="tbody">
<tr>
<audio id="audio'.$i.'" src="mp3/'.$res["song_artist"].'-'.$res["song_title"].'.mp3">
<td><button onclick="download('.$i.')">↴</button></td>
</tr>
</tbody>');
}
I'm trying to download an mp3 file on the click of a button, it downloads, but the file it downloads is not correct, it's a WAY smaller file than the original one (25 bytes), while the original one is 10MB.
It's my first time working with downloading stuff so I'm pretty clueless.
Here's some code:
JS function:
function download(i) {
var audio = document.getElementById("audio"+i);
const blob = new Blob([audio], {type:"octet-steam"});
const href = URL.createObjectURL(blob);
const a = Object.assign(document.createElement("a"), {
href,
style: "display:none",
download: "myAudio.mp3",
});
document.body.appendChild(a);
a.click();
URL.revokeObjectURL(href);
a.remove();
}
Audios are identified by their ID and their file name comes from the data I have in a database.
HTML/PHP
for($i=0; $i<$count; $i++){
$res = mysqli_fetch_array($result);
echo('<tbody id="tbody">
<tr>
<audio id="audio'.$i.'" src="mp3/'.$res["song_artist"].'-'.$res["song_title"].'.mp3">
<td><button onclick="download('.$i.')">↴</button></td>
</tr>
</tbody>');
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您的
元素和下载按钮都是由 PHP 代码生成的,因此您不需要 JavaScript 来执行此操作。
尝试这样的操作:(
我还将您的
标记移到循环之外,以便它包含其中的所有行。)
Since your
<audio>
elements and download buttons are both being generated by your PHP code, you shouldn't need JavaScript to do this.Try something like this:
(I also moved your
<tbody>
tag outside the loop so that it includes all the rows inside it.)https://www.codegrepper.com/code-示例/javascript/javascript+download+image+from+url
https://www.codegrepper.com/code-examples/javascript/javascript+download+image+from+url