问题
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