问题
Here's a simple example that I believe should be working per the docs. The stream plays, but the callbacks don't fire. Am I making a mistake, or is there a bug somewhere between the SDK / API / SoundManager?
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>Sound Cloud API callback test</h1>
<script src="//connect.soundcloud.com/sdk-2.0.0.js"></script>
<script type="text/javascript">
SC.initialize({
client_id: "YOUR_CLIENT_ID"
});
SC.stream(
'/tracks/293',
{
onload: function() { console.log("Does not fire."); },
onplay: function() { console.log("Does not fire."); },
onfinish: function() { console.log("Does not fire."); }
},
function(sound) { sound.play(); });
</script>
</body>
</html>
This is a similar question, but there have been no answers. Soundcloud Javascript SDK 2.0 - Stream onfinish event does not execute
回答1:
When using html5, you can target the audio element directly and bind custom actions to the callback events on that instead. The examples below are roughly equivalent to your SDK events that aren't firing. It's a workaround, but since html5 is the default method, it's reliable for common use including iOS.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>Sound Cloud API callback test</h1>
<script src="//connect.soundcloud.com/sdk-2.0.0.js"></script>
<script type="text/javascript">
SC.initialize({
client_id: "YOUR_CLIENT_ID"
});
SC.stream(
'/tracks/293',
function(sound) {
html5Audio = sound._player._html5Audio;
html5Audio.addEventListener('canplay', function(){ console.log('event fired: canplay'); });
html5Audio.addEventListener('play', function(){ console.log('event fired: play'); });
html5Audio.addEventListener('ended', function(){ console.log('event fired: ended'); });
sound.play();
});
</script>
</body>
</html>
Here's a list of more available html5 media events:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events
回答2:
I'm not able to post comments, so treat this as one. For reasons unknown (to me at least) what you actually get as a sound object in SDK 2 is the player, not a track. It does work properly if you use sdk.js instead.
来源:https://stackoverflow.com/questions/31143925/soundcloud-sdk-api-callback-events-not-firing