Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

javascript - Failed to execute 'play' on 'HTMLMediaElement': API can only be initiated by a user gesture

I'm making a music playing page, where I use SoundManager 2 for AngularJs. I'm using a remote API to get a song URL to play. I enhanced an angular-soundmanager2 click event handler :

element.bind('click', function () {
    if (angular.isFunction(scope.loadFunction)) {
        scope.loadFunction(scope.song, function () {
            $log.debug('adding song to playlist');
            addToPlaylist(scope.song.playDetails);

        })
    } else {
        $log.debug('adding song to playlist');
        addToPlaylist(scope.song);
    }
});

Where I added a part, that calls scope.loadFunction(song,callback) and after this function loads a song URL it calls a callback to give the control back to angular-soundmanager2.

The problem is that on chrome for android I get an error :

Failed to execute 'play' on 'HTMLMediaElement': API can only be initiated by a user gesture.

it doesn't happen if a song has a URL from the beginning and async loading isn't used.

Are there any workarounds for it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had to experiment with Chrome playing sounds. It turned out that even after a user gesture (such as click) it waits for 1000ms and if no sound was played it throws the exception above. In my case the problem was coming from asynchronous track URL loading.

But it also turned out that after the first track is played chrome doesn't care anymore for this 1000ms delay and you can call play programmatically with any timeout you want.

So the solution was to play a micro almost zero-second long muted sound from static resources after the very first time a user clicks on a track and after that load a desired track URL.

Hope it helps or someone finds other solutions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...