0

I am using SoundManager2 to play audio retrieved from SoundCloud. My issue arises when there are multiple of the same track on one page since I only want to create one sound object for each URL.

It seems that upon initialization of each SCPlayer there is not another SoundManager instance in the window since this.player is always null. I think this has something to do with the promise made by the soundcloud client (since its asynchronous) but not know how to go about resolving the issue.

var SCPlayer = function(id, url){
    this.playing = false;
    this.id = id;
    this.elems = $(".player[data-sc-id="+ this.id + "]"); //Find all elems with data attr so all controls of the same sound are affected
    this.btns = this.elems.find(".button");
    this.url = url;
    this.player = window.soundManager.getSoundById('sc_' + this.id); //always null
    this.init()
};

SCPlayer.prototype = {
    init: function(){
        var that = this;
        if (! that.player) {
            that.player = window.soundManager.createSound({
                id: 'sc_' + that.id,
                url: that.url,
                autoLoad: false,
                autoPlay: false
            });
        }
        $(this.btns).on('click', {context: this}, this.onClick);
    },
    onClick: function(ev){
        //Change play controls
    }
};

var init_SCPlayers = function(){
    //Loop through each player element, retrieve the stream url
    //and then create the soundmanager object
    var urls = [];
    $('.player.sc-player').each(function(){
        var id = $(this).data('sc-id');
        SC.get('/tracks/' + id + '/streams').then(function(stream) {
            new SCPlayer(id, stream.http_mp3_128_url)
        });
    })
}; 

1 Answer 1

0

You can retrieve an existing sound from SoundManager2 using getSoundById. The docs for SoundManager2 are here.

that.player = soundManager.getSoundById('sc_' + that._id) || soundManager.createSound(...);
2
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
    – ohmu
    Commented Jun 9, 2016 at 18:56
  • I'm not sure the edit actually did much, because once a person has the function name they can look it up in the docs. Commented Jun 9, 2016 at 20:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.