简体   繁体   中英

User interaction needed to play audio workaround?

Currently I am working on a html5/js music player application. I have many users on mobile devices that have problems with playing the music. According to many websites you need to have user interaction before you can play audio.

Currently this is how I have programmed my music player. I have used the onclick attribute to detect taps/clicks on a play button.

<button onclick = "playaudio('song name');">Play</button>

Then I have code for js to resolve a play url.

var http = new XMLHttpRequest();
var url = '/getsong';
var params = 'name='+songname;
http.open('POST', url, true);


http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {
    var snd=document.getElementsByTagName("audio")[0];
    snd.src = http.responseText;
    snd.load();
    snd.play();
    }
}
http.send(params);

This works fine on a computer but on mobile users have to click the pause/play button to start the music. Is there any workaround for the user interaction requirement, because I want to implement a remote play system like Google Cast/Spotify Connect.

Currently I don't have access to the complete code so this is just the core part of the music player.

Also I need to make a playlist feature but due to this, it seems quite impossible to play the next track in the playlist without user interaction.

Previously asked question said audio autoplay is not allowed on some mobile browser, you can implement, there are several workarounds.

Audio Tag Autoplay Not working in mobile

And yes, regarding the player, you can opt for an open source HTML5 Player, Amplitude.js which supports playlist as well as next song plays without user interaction based on playlist, you can check a demo on their website

https://521dimensions.com/open-source/amplitudejs

Refer to code on their GitHub:

https://github.com/521dimensions/amplitudejs

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