alex
alex

Reputation: 157

Soundcloud custom player not playing on mobile safari after user event

This is a possible duplicate of this question, but I need an example of how to make it work. The following works in desktop browsers, but doesn't in mobile safari (I'm testing in iOS 6.1.2).

I've read a lot about mobile safari needing user interactions to play a sound, but that's exactly what I have here: a button click fires function to stream the sound.

Can anyone point me in the right direction?

<body>
  <div class="container" style="padding:20px">
    <div class="sixteen columns">
      <input type="button" href="#" id="stream" class="big button" value="Stream It Again, Sam" onclick="playTrack()"/>
      <div class="console"></div>
    </div>
  </div>

  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  <script src="//connect.soundcloud.com/sdk.js"></script>
  <script>
  SC.initialize({
    client_id: "MY-CLIENT-ID"
  });

  function playTrack(){
    SC.stream("/tracks/293", {
      useHTML5Audio: true,
      preferFlash: false
    }, function(sound) {
      sound.play();
      $('.console').text('button clicked');
    });

  }

  </script>
</body>

Here is a Live Example

Upvotes: 2

Views: 2368

Answers (1)

Misha Reyzlin
Misha Reyzlin

Reputation: 13906

In your case the user action and call to play sound happen in different call stacks.

You'd need to modify your JS to something like this:

SC.initialize({
  client_id: "YOUR_CLIENT_ID"
});

var soundToPlay; 
// first do async action
SC.stream("/tracks/293", {
  useHTML5Audio: true,
  preferFlash: false
}, function(sound) {
  soundToPlay = sound;
  document.querySelector('input').disabled = false;
});

function playTrack () {
  soundToPlay.play();
}

This way the sound is loaded (asynchronous action) before the action is possible (button is disabled by default) and then you can play it and call it directly.

Here's a working example – http://jsbin.com/esadon/1/edit

Upvotes: 1

Related Questions