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>');
}
CodePudding user response:
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:
<tbody id="tbody">
<?php
for($i=0; $i<$count; $i ){
$res = mysqli_fetch_array($result);
$filePath = "mp3/{$res["song_artist"]}-{$res["song_title"]}.mp3";
?>
<tr>
<td><audio src="<?=$filePath?>"></td>
<td><a href="<?=$filePath?>" download>↴</button></td>
</tr>
<?php
}
?>
</tbody>
(I also moved your <tbody>
tag outside the loop so that it includes all the rows inside it.)
CodePudding user response:
You can try this. Here you have to provide audio file source instead of image source. I did not try this code, But i assure you to it should work!
https://www.codegrepper.com/code-examples/javascript/javascript download image from url