Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

553
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda