I'm working on a progressive web app which is mainly used on desktop and android to play music. On PC, everything works fine. On Android, it suddenly stopped working. After some research I found this update regarding an autoplay policy change in chrome.
The gist is that you cannot just play media anymore without a user interaction.
Before this update I had my AudioContext which gets created onload
and afterwards is just used. This doesn't work anymore.
The update posts states this:
An AudioContext must be created or resumed after the document received a user gesture to enable audio playback
So I made some adjustments to .suspend()
and .resume()
the context accordingly onPlay
and onPause
of my application.
On PC this still works, on Android it doesn't. Am I missing something?
Edit 1:
I found this site stating the following:
Under the new policy media content will be allowed to autoplay under the following conditions:
a) The content is muted, or does not include any audio (video only)
b) The user tapped or clicked somewhere on the site during the browsing session
c) On mobile, if the site has been added to the Home Screenby the user
d) On desktop, if the user has frequently played media on the site, according to the Media Engagement Index
I understand this to be true if one of those matches. In my case b) and c) are fulfilled. So I guess this should work?
You need to call resume() on the audio context on a user action event such as button click. I am guessing your problem was the location of where you called context.resume() was not on a user interaction event. You can't just call it from onLoad.
Sample code:
// Existing code unchanged.
window.onload = function() {
var context = new AudioContext();
// Setup all nodes
...
}
// One-liner to resume playback when user interacted with the page.
document.querySelector('button').addEventListener('click', function() {
context.resume().then(() => {
console.log('Playback resumed successfully');
});
});
Docs describe it here: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio