使用自定义按钮播放SoundCloud流

时间:2017-03-08 19:01:23

标签: javascript html css soundcloud

我在使用自定义按钮播放SoundCloud流时遇到问题。

这是我正在研究的CodePen: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

  });
});

谢谢!

1 个答案:

答案 0 :(得分:1)

这是我的工作片段,虽然它不完整(我正在吃饭,但在看到你的评论之前还要完成它)基本上剩下的就是添加一个if-else语句来查看如果音频正在播放,如果正在播放,则将其暂停。在暂停时添加暂停类(但如果它在那里,则将其删除)。

目前,在fiddle图标切换为暂停,但播放没有暂停...在摘录中我添加了一个不会切换的替代版本,但是在那里更接近别的 - 如果(我还没看过API)

&#13;
&#13;
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();
      }
    });
  });
});
&#13;
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;
}
&#13;
<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>
&#13;
&#13;
&#13;