Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

560
Vistas
Download audio file from html with javascript function

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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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.)

about 4 years ago · Juan Pablo Isaza Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda