简体   繁体   中英

How to turn binary from server back into audio file?

I am using express's res.sendFile() to send an.mp3 file from my server to my client as a response to a post request.

I have been unable to transform the string of data (binary, I think?) back into a usable format for my web application. (ideally, use it as an <audio> element).

When I hit this route using Postman, it appears to be working- the 'body' of the response opens up a working audio player within Postman's app (pictured below). This tells me there is no issue server side. In my client code, I've tried to make a new Blob using the data property of my server response, and then use that Blob to source an HTML <audio> element. Here is what that looks like starting from my axios.post() response:

.then((res) => {
  const blob = new Blob([res.data], {type: 'audio/mpeg'})
  sendBlobToAnotherComponent(blob)
})

//== send the blob to the appropriate .jsx element (using React) ==\\

<audio
  controls
  src={URL.createObjectURL(blob)}>
</audio>

I'm fairly confident I am just building this Blob incorrectly but can't figure it out for the life of me. It's infuriating that Postman does this automatically lol..: but also give me hope! Thanks for any help :)

e.headers on the response from server in Postman

ea look at my logs of the res.data object and the blob I create

Two things you can do.

  1. If you are getting blob you can directly use it like below- <audio controls src="data:audio/mp3;base64, ...
  2. In audio tag you can directly pass the URL like below-

 <audio src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/858/outfoxing.mp3" controls />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM