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

前端 未结 4 1119
情话喂你
情话喂你 2020-12-05 10:29

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 eve

4条回答
  •  温柔的废话
    2020-12-05 11:02

    Here is how I embeded this solution into soundmanager2 :

    Create a function :

    function playMicroTrack(scope, angularPlayer) {
    if (!scope.$root.isInitialized) {
        soundManager.createSound({
            id: '-1',
            url: '../../assets/lib/microSound.mp3'
        });
        soundManager.play('-1');
        scope.$root.isInitialized = true;
        }
    }
    

    Then inside the play directive use :

    ngSoundManager.directive('playAll', ['angularPlayer', '$log',
    function (angularPlayer, $log) {
        return {
            restrict: "EA",
            scope: {
                songs: '=playAll'
            },
            link: function (scope, element, attrs) {
                element.bind('click', function (event) {
    
                    playMicroTrack(scope, angularPlayer);
    
                    //first clear the playlist
                    angularPlayer.clearPlaylist(function (data) {
                        $log.debug('cleared, ok now add to playlist');
                        //add songs to playlist
                        for (var i = 0; i < scope.songs.length; i++) {
                            angularPlayer.addTrack(scope.songs[i]);
                        }
    
                        if (attrs.play != 'false') {
                            //play first song
                            angularPlayer.play();
                        }
                    });
                });
            }
        };
    }
    ]);
    

    In my case soundManager.play contains a piece of code that sends an async call to server to fetch a track url. This was causing the issue.

    Hope this helps

提交回复
热议问题