2

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.')">&#8628</button></td>
  </tr>
</tbody>');
}    

2
  • Why are you doing this with JavaScript? Why can't you use a simple download link?
    – Moshe Katz
    Commented Feb 24, 2022 at 18:19
  • I do not know how to do that, and since each audio is individually id'd by a variable (i) I thought it'd be easier to do on javascript.
    – yksi
    Commented Feb 24, 2022 at 19:20

2 Answers 2

2

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>&#8628</button></td>
  </tr>
<?php
}
?>
</tbody>

(I also moved your <tbody> tag outside the loop so that it includes all the rows inside it.)

1

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

2
  • I tried this, however it did not work, when I call the function, I get an error saying "(source) is not defined" I put on the source the link that links to the mp3 file
    – yksi
    Commented Feb 24, 2022 at 19:38
  • The issue is with passing the source from the html/php to javascript and not the download itself i think
    – yksi
    Commented Feb 24, 2022 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.