I'm having trouble playing a SoundCloud stream with a custom button.
Here's a CodePen I'm working on: https://codepen.io/tremolocreative/pen/Zepjwm
HTML
<script src="https://connect.soundcloud.com/sdk.js"></script>
<audio id="soundcloudPlayer"></audio>
<button></button>
CSS
button {
background: url(//cdn.shopify.com/s/files/1/1055/5530/t/8/assets/play-pause-sprite.svg?2157621096199230646);
background-size: cover;
background-position: top left;
background-repeat: no-repeat;
width: 20px;
height: 20px;
border: 0;
outline: 0;
display: block;
}
button.pause-sprite {
background-position: top right;
}
JS
var client_id = '278594df9a311b2a1a56251b3a2b0fbe';
var track_id = '293605256';
SC.initialize({
client_id: client_id
});
SC.get('/tracks/' + track_id, {}, function(sound) {
$('#soundcloudPlayer').attr('src', sound.stream_url + '?client_id=' + client_id);
$('button').on('click', function() {
$(this).toggleClass('pause-sprite');
$('#soundcloudPlayer').play(); // Play track
});
});
Thanks!
Here's my working snippet, although it's not complete (I was having dinner, was gonna finish it before I saw your comment) Basically all that remains is to add an if-else statement to see if the audio is playing, and if it's playing then pause it. Add the pause class on pause (but remove it on play if it's there).
At the moment, in the fiddle the icon toggles to pause but the playing doesn't pause.. in the snippet i put an alternative version that doesn't toggle but there's a closer else-if (i didn't look at the API yet)
var client_id = '278594df9a311b2a1a56251b3a2b0fbe';
var track_id = '293605256';
SC.initialize({
client_id: client_id
});
$(document).ready(function() {
$("#stream").on("click", function() {
SC.stream("/tracks/" + track_id, function(sound) {
if (sound.currentTime > 0) {
$('button').addClass('pause-sprite');
sound.pause();
} else {
$('button').removeClass('pause-sprite');
sound.play();
}
});
});
});
button {
background: url(//cdn.shopify.com/s/files/1/1055/5530/t/8/assets/play-pause-sprite.svg?2157621096199230646);
background-size: cover;
background-position: top left;
background-repeat: no-repeat;
width: 20px;
height: 20px;
border: 0;
outline: 0;
display: block;
}
button.pause-sprite {
background-position: top right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//connect.soundcloud.com/sdk-2.0.0.js"></script>
<div id='player'>
<button href="#" id="stream">
</button>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With