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.
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:
<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
});
});