2021年5月3日星期一

HTML5 audio on android chrome, not playing unless an alert() is called

I've searched other questions and it seems like this is a problematic area. Unfortunately no one else seemed to have the same issue as me.

I'm essentially trying to trigger an mp3 when a button is clicked. I'm having no problem with desktop browsers but when I try on android I get nothing. I added an alert() just to check that the onclick function was firing and to my surprise after dismissing it the audio plays.

I'm aware that user interaction is required in order to trigger audio but I thought an onclick event would suffice. Is there another gotcha that I am missing?

I've included two snippets to display the difference.

This version works on desktop but not android

let btn = document.querySelector('button')  let audio = new Audio('https://archive.org/download/BirdCall/chrysococcyx-basalis.mp3')    const handleClick = (file) => {    if (file.paused) {      file.play();    } else {      file.currentTime = 0;    }  }      btn.onclick = () => handleClick(audio)
<h1>Working On Desktop</h1>    <button>Bird Call</button>

This version works on android

let btn = document.querySelector('button')  let audio = new Audio('https://archive.org/download/BirdCall/chrysococcyx-basalis.mp3')    const handleClick = (file) => {    alert('Audio will play.')    if (file.paused) {      file.play();    } else {      file.currentTime = 0;    }  }      btn.onclick = () => handleClick(audio)
<h1>Working On Android Chrome</h1>  <button>Bird Call</button>

Any input is greatly appreciated.

https://stackoverflow.com/questions/67299052/html5-audio-on-android-chrome-not-playing-unless-an-alert-is-called April 28, 2021 at 07:07PM

没有评论:

发表评论