3

I'm building app to listen sound/music from the list.

Each item has an id to download mp3 file from API.

How can I get the mp3 from API and then correctly play the audio? Do I need to store the file or there is a way to dynamically load and play this file?

I'm receiving error like play audio error: DOMException: Failed to load because no supported source was found.

Here is my code:

  const playAudio = async (id) => {
    try {
      const response = await axiosClient.get(`api/getaudio/id/${id}`)
      const mp3 = new Blob([response.data], { type: 'audio/mp3' })
      const url = window.URL.createObjectURL(mp3)
      const audio = new Audio(url)
      audio.load()
      await audio.play()
    } catch (e) {
      console.log('play audio error: ', e)
    }
  }
  return (
    <ul>
      {props.topList.map(item => (
        <li onClick={() => playAudio(item.id)}>{item.title}</li>
      ))}
    </ul>
  )
Robson
  • 1,207
  • 3
  • 21
  • 43
  • 2
    Did you look at this: https://stackoverflow.com/questions/9563887/setting-html5-audio-position/26865633#26865633 . You need to pass `responseType: 'blob'` to your axios request. – Adolfo Onrubia Nov 21 '19 at 22:33
  • 1
    @AdolfoOnrubia Yep, that was missing. Really quick help, and it works like a charm! Thanks :D – Robson Nov 21 '19 at 22:36

1 Answers1

0
const playRecord = (url: string, data: object) => {

  const config = {
    headers: {
      responseType: 'blob',
      Accept: "application/force-download",
    },
  };
  return client.post(url, data, config).then((response: any) => {
    let blob = new Blob([response.data], { type: "audio/mp3" }),
      downloadUrl = window.URL.createObjectURL(blob);
      const audio = new Audio(downloadUrl)
      audio.load()
      audio.play()

  }).catch(handleError);
};
susindu
  • 51
  • 4