简体   繁体   中英

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.

That's a strange problem. I tried it on an old android phone and couldn't reproduce the issue (the audio plays without any need for an alert box). I can't see any obvious explanation, but perhaps chrome is waiting for user input before loading the audio file, your device is failing to start loading it quickly enough, then it's hitting a timeout. The alert box might just introduce enough delay. It's a long shot, but you could try adding an extra interaction for the user to load the audio first, like this:

 let load = document.querySelector("#load"); let play = document.querySelector("#play"); // different audio file used in this snippet, because archive.org is // blocked by my ISP... damn internet censorship let audio = new Audio("https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3"); play.onclick = () => { audio.play(); } load.onclick = () => { audio.load(); } audio.oncanplay = () => { load.disabled = true; play.disabled = false; };
 <button id="play" disabled>Play</button> <button id="load">Load</button>

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