Search code examples
javascriptfetch-apihtml5-audio

How do i stream an audio from a database and play on a phone when i retrieve the link using fetch api?


I currently have the following in my html

<audio id="result-audio"></audio>
<button onclick = "playBack()"><i class="fas fa-volume-up"></i></button>

In my javascript i have the following


 fetch(`${url}`)
    .then((response) => {
      return response.json();
    }).then((data) => {
        document.getElementById("result-audio").setAttribute("src", `${data['File']}`);
})

function playBack(){
    document.getElementById("result-audio").play();
}

where url goes to a database and retrieves a link for an audio file which is inserted into the source of the audio element. Retrieving the link works fine and clicking the button the file plays ok on a laptop but it does not on any phone. How best can i solve the issue of it not playing on the phone or is there another approach i need to take?

EDIT I am not looking to make an audio player. I am looking for example the audio you get when you search the meaning of a word on google where it pronounces that word.


Solution

  • If you want to play audio on both desktop and mobile devices, you should ensure that the audio format you're using is compatible with a wide range of browsers and devices. You can also use the HTML5 audio element's controls attribute to provide a built-in audio player interface for easier playback on both desktop and mobile.

    Here's how you can modify your code:

    1. Make sure your audio file is in a widely supported format, such as MP3.
    2. Modify your HTML to include the controls attribute for the audio element:
    <audio id="result-audio" controls></audio>
    <button onclick="playBack()"><i class="fas fa-volume-up"></i></button>
    
    function playBack() {
      const audioElement = document.getElementById("result-audio");
      if (audioElement.paused) {
        audioElement.play();
      } else {
        audioElement.pause();
      }
    }
    
    // Use the 'loadedmetadata' event to start playing once the audio is loaded
    fetch(`${url}`)
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        const audioElement = document.getElementById("result-audio");
        audioElement.setAttribute("src", `${data['File']}`);
        audioElement.addEventListener("loadedmetadata", function () {
          playBack(); // Start playing once audio is loaded
        });
      });