0

I retrieve an audio data from an external url and I need to return audio with an api call. When I go to that endpoint like http://localhost:3000/audio from browser, I need to listen to that audio.

I've got stuck in this situation


async function getData(url: string) {
  return new Promise(async (resolve, reject) => {
    await axios.get(url)
      .then(resp => {
        resolve(resp.data)
      })
      .catch(error => {
        reject(error)
      })
  })
}

app.get('/audio', async (req: Request, res: Response) => {

   const audio = await getData('external_url')
   return res.status(200).send(audio)
})

It prints on browser this (I've just copied a part of it. If it's needed I'll write the whole thing):

�U��]UV��U�U�U�U���U���UF�DU�
UUyՕU�ՑU���U��WU�U�DU�ՔU���U���U��kUU�U�ՕU�ՕU���U��[UzU{U���U�����U���U���U�U�U���U�UU
UUtU�U�U�U�U�����UUUUAU�U�U�U�U�U�U�UlU�Us�sUXU�U���U���U@�uU�OU���U���U���U���U���U�UWU_Ua�UUU�՚U�U�UF��U�Ug�U�U�ՐU�U���U���UF�oU�bU���Uw�{U�U�ՔU��UUs�XURUZ�ZUWU�U���U

What should I do after that. I've found some post about creating files and serving them. But I could not applied them on my code.

Save byte array to file node JS Send audio from Node backend to frontend

How can we create an audio file from that bytes array and serve it from that endpoint?

  • Don't proxy the data... just redirect the client and let them access it directly. If you are going to proxy the data, then you need to also support ranged requests, like any other proxy connection. – Brad Mar 24 '23 at 00:33
  • If audio data is "printed" on response page, I guess you are missing correct response headers – pierpy Mar 24 '23 at 03:46
  • @pierpy hello, thank you for your reply, `const length = (audio as Uint8Array[]).length` `res.setHeader('Content-Range', 'bytes 0-${length - 1}/${length}')` `res.setHeader('Accept-Ranges', 'bytes')` `res.setHeader('Content-Length', length)` `res.setHeader('Content-Type', 'audio/wav')` I've added these headers to my response. Is there something missing? – Oğuz Öztınaz Mar 24 '23 at 07:57
  • @OğuzÖztınaz your axios req fetches a physical audio file? Or it's created on the fly? Maybe that's the problem... Response is not a well formed audio file.... – pierpy Mar 24 '23 at 18:50

0 Answers0