TonalDev
TonalDev

Reputation: 583

Randomise stream links in jPlayer

I have a modded jPlayer that connects to a shoutcast/icecast source.

I want to make jPlayer randomly connect between 2 or more url's upon opening the page.

For example if i have 2 links:

  1. www.example.com:8000/live
  2. www.example.com:8000/live2

Then i need jPlayer to randomly choose one of them when opening the page. The purpose is to prevent over-load on one server.

How should i go about it in the jQuery code?

jQuery:

$("#jquery_jplayer_1").jPlayer({
        ready: function(event) {
            $(this).jPlayer("setMedia", {
                mp3: "http://www.example.com:8000/live"
            }).jPlayer("play");
        },
        swfPath: "js/",
        wmode: "window",
        solution: "flash,html",
        supplied: "mp3",
        preload: "none",
        volume:0.75,
        cssSelectorAncestor: "",
        cssSelector: {
                play: "#play",
                pause: "#pause"
        }
    });

    $("#jquery_jplayer_1").bind($.jPlayer.event.pause, function(event) {
        $(this).jPlayer("clearMedia");
        $(this).jPlayer("setMedia", {
                mp3: "http://www.example.com:8000/live"
        });
    });

Upvotes: 0

Views: 300

Answers (2)

Alexander
Alexander

Reputation: 23537

Answering your question you can do the following.

var servers = ["www.example.com:8000/live", "www.example.com:8000/live2"];
var server = servers[Math.floor(Math.random() * servers.length)];

$(this).jPlayer("setMedia", {
  mp3: server
});

Notwithstanding this is not an optimal way to address your real problem:

The purpose is to prevent over-load on one server.

You should consider using load balancing.

Upvotes: 2

Bozho
Bozho

Reputation: 597234

You can get one of X random urls in either your server-side language or in javascript. Then simply pass the randomized value to mp3:

var randomUrl = getRandomUrl();
$("#jquery_jplayer_1").bind(...) {
       mp3: randomUrl;
}

Upvotes: 1

Related Questions