简体   繁体   English

JavaScript-Spotify API,获取播放列表曲目

[英]JavaScript - Spotify API, fetching playlist tracks

I am using spotify api to search for the playlists and then display them in my mobile application. 我正在使用Spotify api搜索播放列表,然后在我的移动应用程序中显示它们。 I am using Ajax to get the information from the api which works fine yet I can't seem to be able to populate the div with the results and make it possible for the application to play music snippets as it doesn't want to allow event listeners. 我正在使用Ajax从api中获取信息,该信息可以正常工作,但似乎无法用结果填充div,并且由于应用程序不想允许事件播放音乐片段,因此我无法使用该信息听众。 You won't be able to see all the variables used but everything before this code works perfectly fine. 您将无法看到所有使用的变量,但是此代码之前的所有内容都可以正常工作。

var audioObject = null;
//Spotify page
$(document).on('pagecreate', '#spotify', function(){
console.log("Spotify");
$('#search').on('click', function() {
    //e.preventDefault();
    searchstring = cweather;

    if (!searchstring){
        console.log('no input');
        return;
    }
    console.log(searchstring);
    searchPlaylist(searchstring);
});

});

var userId;

var searchPlaylist = function () {
$.ajax({
    url: 'https://api.spotify.com/v1/search',
    headers: {
        Authorization: 'Bearer ' + spotifyAccessToken,
    },
    data: {
        q: searchstring,
        type: 'playlist',
        market: 'GB',
        offset: '0',
        limit: '5',
    },
    success: function (response) {
        console.log(response);

        var items = response.playlists.items;
        var resultsintohtml = '';

        $.each(items, function(index) {
            var id = items[index].id;
            var name = items[index].name;
            //var image = items[index].image[1].url;
            userId = items[index].owner.id;
            console.log(id, name, userId);
            resultsintohtml += '<div style="backgroundColor="red"" data-album-id="' + id + '" class="cover"></div>';
        });

        console.log(resultsintohtml);
        document.getElementById("results").innerHTML = resultsintohtml;

        addclickevents();
    }
});
};

var fetchTracks = function (playlistsId, userId, callback) {
$.ajax({
    url: 'https://api.spotify.com/v1/users/' + userId + '/playlists/' + playlistsId,
    headers: {
        Authorization: 'Bearer ' + spotifyAccessToken,
    },
    success: function (response) {
        console.log(response);
        callback(response);
    }
});
};

var addclickevents = function () {
$('.cover').click(function (e){
    console.log('get song');
    var target = $(this);

    if (target.hasClass('playing')) {
        audioObject.pause();
    } else {
        if (audioObject){
            audioObject.pause();
        }

        fetchTracks(target.data('playlist-id'), function (data) {
            audioObject = new
            Audio(data.tracks.items[0].preview_url);
            audioObject.play();
            target.addClass('playing');             
        });
        audioObject.addEventListener('pause', function(){
            target.removeClass('playing');
        });
    }
});
};

As this code is used I get following errors: Errors I have tried renaming the variables yet I get the very same error. 使用此代码时,我得到以下错误: 错误我曾尝试重命名变量,但是却遇到了同样的错误。 I have double checked if there is any missing information from the spotify yet I am using all the available ID's already. 我已经仔细检查了Spotify是否缺少任何信息,但我已经使用了所有可用的ID。 Thanks in advance. 提前致谢。

Update: looking closer to your code, I just noticed fetchTracks expects 3 parameters and you're passing only 2. The second parameter should be userId and the third should be the callback. 更新:更接近您的代码,我刚刚注意到fetchTracks需要3个参数,而您只传递2个参数。第二个参数应该是userId ,第三个参数应该是回调。 I don't have a clue what your userId is, but, assuming it's 123 you should run the function like this: 我不知道您的userId是什么,但是,假设它是123 ,则应运行以下函数:

...
fetchTracks(target.data('playlist-id'), "123", function (data) {
  audioObject = new Audio(data.tracks.items[0].preview_url);
  audioObject.play();
  target.addClass('playing');             
  audioObject.addEventListener('pause', function(){
    target.removeClass('playing');
  });
});
...

Considering, your code is, most likely, calling a broken URL from Spotify's point of view (which should show up as an error in your console - most likely, a 404 but possibly also 403 or 422 ). 考虑到您的代码很可能是从Spotify的角度调用了损坏的URL(应该在控制台中显示为错误-最有可能是404但也可能是403422 )。


Initial answer: 初步答案:

Assuming the code above is what's generating the error, at line 87 (in the above snippet), you're trying to add an event listener on audioObject . 假设上面的代码是导致错误的原因,那么在第87行(在上面的代码段中),您尝试在audioObject上添加事件侦听audioObject According to the error, audioObject is not a DOM element, but null . 根据错误, audioObject不是DOM元素,而是null So you might want to check if the element supports the method before applying it: 因此,您可能需要在应用元素之前检查该元素是否支持该方法:

...
if (audioObject)
   audioObject.addEventListener('pause', function(){
     target.removeClass('playing');
   });

or... 要么...

if (audioObject instanceof Element)
   audioObject.addEventListener('pause', function(){
     target.removeClass('playing');
   });

Note (as future reference): whenever you decide to post images of code instead of the code itself on [SO], expect being down-voted. 注意 (作为将来的参考):每当您决定在[SO]上发布代码图像而不是代码本身时,都应该投票赞成。

Another note : the above does not fix the logic of your application, which is clearly broken (or at least not working as intended). 另一个注意事项 :上面的内容无法解决您的应用程序的逻辑,该逻辑显然已损坏(或至少未按预期工作)。 It just avoids executing the code when it would generate an error. 它只是避免在可能产生错误的情况下执行代码。


You probably want add the event listener inside fetchTracks() : 您可能想要在fetchTracks()添加事件侦听器:

...
fetchTracks(target.data('playlist-id'), function (data) {
  audioObject = new Audio(data.tracks.items[0].preview_url);
  audioObject.play();
  target.addClass('playing');             
  audioObject.addEventListener('pause', function(){
    target.removeClass('playing');
  });
});
...

..., but, without a minimal working example I can't be sure. ...,但是,如果没有最小的工作示例,我无法确定。

If audioObject is only assigned a value in the callback of fetchTracks , it won't be defined when audioObject.addEventListener is called. 如果audioObject只在回调赋值fetchTracks ,它不会被当定义audioObject.addEventListener被调用。

When you click on a .cover , the event listener is called. 当您单击.cover ,将调用事件侦听器。 If the cover does not have the "playing" class, then: 如果封面没有“演奏”类,则:

  • the audioObject is still null audioObject仍然为null
  • fetchTracks will be called but the callback will not fire until the response is received fetchTracks将被调用,但在收到响应之前不会触发回调
  • audioObject.addEventListener will be called but the audioObject is null audioObject.addEventListener将被调用,但 audioObjectnull
  • the response for fetchTracks come back, and in the callback you set audioObject to be an instance of Audio fetchTracks的响应返回,并在回调中将audioObject设置为Audio的实例

Is there any reason why you chose to add the event listener outside of the callback? 您为什么选择在回调之外添加事件侦听器?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM