JavaScript Soundcloud API integration - cannot read property 'uri' of undefined

我们两清 提交于 2019-12-13 06:03:46

问题


I'm trying to copy the code from this video. It's old so I changed the url for the SDK. Here's the JS code:

function playSomeSound(genre){
SC.get('/tracks', {
    genres: genre,
    bpm: {
        from: 40
    }
}, function(tracks){
    var random = Math.floor(Math.random() * 49);
    SC.oEmbed(tracks[random].uri, { auto_play: true}, document.getElementByID('target'));
});
}

window.onload = function(){
SC.initialize({
    client_id: '1166055b8d5ca23b9c265bf8846d1102'
});

var menuLinks = document.getElementsByClassName('genre');
for (var i = 0; i < menuLinks.length; i++){
    menuLinks(i).onclick = function(e){
        e.preventDefault();
        playsomesound(menuLinks.innerHTML);
    };
}

On line 9 that starts SC.oEmbed(....), it gives the error "Cannot read property 'uri' of undefined."

Can someone tell me what is wrong or point to a resource that might help?

Thanks


回答1:


Your random number is sometimes higher than the returned tracks array. Therefore if you only have 10 tracks returned, you can not access uri of track > 10.

You can simply add the limit to 50. Or add a function which checks that random wont be bigger than the tracks.length.

Here is a working fiddle:

function playSomeSound(genre){
SC.get('/tracks', {
    genres: genre,
    bpm: {
        from: 40
    }, 
    limit: 50
}, function(tracks){
    var random = Math.floor(Math.random() * 49);
    console.log(random, tracks.length);
    SC.oEmbed(tracks[random].uri, { auto_play: true}, document.getElementById("target"));
});
}

window.onload = function(){
SC.initialize({
    client_id: '1166055b8d5ca23b9c265bf8846d1102'
});
}    

playSomeSound('house');
/*
var menuLinks = document.getElementsByClassName('genre');
for (var i = 0; i < menuLinks.length; i++){
    menuLinks(i).onclick = function(e){
        e.preventDefault();
        playsomesound(menuLinks.innerHTML);
    };
}
*/ 

http://jsfiddle.net/iambnz/yy8hwg76/



来源:https://stackoverflow.com/questions/32533242/javascript-soundcloud-api-integration-cannot-read-property-uri-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!