Soundcloud custom player add and play song dynamically - javascript

I am using soundcloud custom player to create a player which can play all the songs on
my site. This works pretty good when i just place static url of any track or a post. But what i want is to add the song to the list dynamically.
I have done lots of research but couldn't get it to work. What i want is there would be multiple players through out the site. kind of(http://soundcloud.com) and there would a main player on the top(like soundcloud) which would play around 100 latest songs on site and there would be a smaller player clicking on which will just append that song to the list and start playing that song.
I am not sure if this is the right process. If any one can just give me any hint how i can proceed further then it would be great.

After doing a lot of research in the Wiki, studying the code in sc-player.js, and some testing, I think I've found a solution to your problem. Try the following:
First, add this code to sc-player.js file, just before the comment // the default Auto-Initialization (this line is just like 8 lines before the end of the file)
$.scPlayer.loadTrackInfoAndPlay=function($elem,track){
var playerObj=players[$elem.data('sc-player').id];
playerObj.tracks.push(track);
var index =playerObj.tracks.length-1;
var $list=$(playerObj.node).find('.sc-trackslist');
var $artworks=$(playerObj.node).find(".sc-artwork-list");
// add to playlist
var $li=$('<li>' + track.title + '<span class="sc-track-duration">' + timecode(track.duration) + '</span></li>')
.data('sc-track', {id:index})
.appendTo($list);
// add to artwork list
$('<li></li>')
.append(artworkImage(track, true))
.appendTo($artworks)
.data('sc-track', track);
$li.click();
}
The function above, takes care of adding a new track to the playlist and starts playing the track.
Now, suppose you have this html code for the players
<h2>Top Player</h2>
<div id="topPlayer">
<div class="sc-player">
My live track
On the bridge
</div>
</div>
<h2>Small Player</h2>
<div id="smallPlayer">
Soulhack
</div>
Make sure to wrap your sc-players in a div, preferably with an id, so you can reference the players later in Javascript:
Finally, you can use this Javscript code to detect when a track is clicked in smallPlayer and add and play that track in topPlayer
$(function(){
var $topPlayer=$("#topPlayer .sc-player");//Top player
var $smallPlayer=$("#smallPlayer .sc-player");//Small Player
$smallPlayer.on("onPlayerInit.scPlayer",function(evt){//When player is ready
$smallPlayer.on("onPlayerTrackSwitch.scPlayer",function(evt,track){//Listen to track switch in smallPlayer
setTimeout(function(){//Wait a bit, to avoid playing problems between both players
$.scPlayer.loadTrackInfoAndPlay($topPlayer, track);
},250);
});
});
});
And that's It!.
EDIT
If you only have the url of the song to be added, you can do the following:
First, add this other function to sc-player.js file, just after the previous loadTrackInfoAndPlay function:
$.scPlayer.loadTrackUrlAndPlay=function($elem,url){
var apiUrl = scApiUrl(url, apiKey);
$.getJSON(apiUrl, function(data) {
if(data.duration){
data.permalink_url = url;
$.scPlayer.loadTrackInfoAndPlay($elem,data);//Call the previous function
}
});
}
Now, suppose you have this code for the urls of the songs:
<p>
The links <br />
<a class="songUrl" href="https://soundcloud.com/feintdnb/coldplay-fix-you-feint-bootleg">Coldplay-Fix you</a><br />
<a class="songUrl" href="https://soundcloud.com/nct-1/nct-you-preview-out-soon-for">NCT - You</a><br />
<a class="songUrl" href="https://soundcloud.com/tufftouch/devil-eyes-konflix-feat-leanne">Konflix - Devil Eyes</a>
</p>
Then, you can use this code to add the song to the playlist and start playing it (or just playing it if it already exists)
$(".songUrl").click(function(event){
event.preventDefault();
var url=$(this).attr("href");//Url of the song
//If the song is in the tracks list, this line finds it
var $theSong=$topPlayer.find(".sc-trackslist a[href='"+url+"']");
if($theSong.length==0){//
$.scPlayer.loadTrackUrlAndPlay($topPlayer,url );
}else{
$theSong.parent().click();//Fire click = play the song
}
});
And that's all that is needed.

I'll try to give you as much info as I can, but as there's nowhere to start, I'm not sure if it will help. It's important to start with the wiki. This is what I could extract from there:
Dynamic Track Loading
The player can be created on the fly, and therefore any url can be added. In order to do that, the following methods are available:
Appending directly to the element:
$('div.your-container-class').scPlayer({
links: [{url: "http://soundcloud.com/matas/hobnotropic", title: "http://soundcloud.com/matas/hobnotropic"}]
});
or Create the object and append where you want:
var $myPlayer = $.scPlayer({
links: [{url: "http://soundcloud.com/matas/hobnotropic", title: "http://soundcloud.com/matas/hobnotropic"}]
});
$myPlayer.appendTo($('#somewhere-deep-in-the-dom'));
A little example I just found:
$(function() {
$('a.sc-remote-play1').on('click', function(event) {
$('.sc-player').scPlayer({
links: [{url: "http://soundcloud.com/matas/hobnotropie", title: "Hobnotropic"}],
});
});
});
I believe that should solve the dynamic track loading.
Initializing scPlayer
It's important to take into account that the scPlayer must load itself, and therefore will not work if you change the url directly with jQuery. In order to initialize the scPlayer, which takes place once the DOM has loaded, you can use
$('a.your-link-class').scPlayer();
or
$('div.your-container-class').scPlayer();
Default loading takes place, as I said, on DOM load with the following method
$('a.sc-player, div.sc-player').scPlayer();
This default behaviour can be changed as follows:
$.scPlayer.defaults.onDomReady = function(){
// Default behaviour wanted. Per default we have:
$('a.your-link-class').scPlayer();
};
That's what I've got up to now. Try to get the scPlayer working (loading songs dynamically) and we can follow with the data load and all that stuff.

Related

How to make all website dead links redirect to particular page via JS?

Here's the issue:
Got multiple internal links on the web, still not connected to actual html files.
Im working with local files for the time being
Wanna make js redirect all of the dead links to one particular page (let's call the file: 404-error-page.html) up until I will finish the rest of html files to make those dead links active again
Purpose: wanna keep user away from seeing 404 blank page and instead show em some temporary page (404-error-page.html)
Sorry if that's messy - 1st time adding a question here.
HTML
<html><body><a href="random-link-directing-to-a-non-existing-page"></body></html>
JS
$('a').on('click', function(event) {
var $element = $(event.target);
var link = "404-error-page.html";
if(result.broken) {
if(result.http.response && ![undefined, 500].includes(result.http.response.statusCode)) {
event.preventDefault();
document.location.href = link;
}
}
});
I've already tried some alterations of this code but it's not working for me.
Firstly, need to make this functional on local files and then ofc online.
Any ideas?
Set the data-dead-link attribute to all your unfinished link tag as the follow.
Correct Link
<a data-dead-link>Dead Link</a>
<a data-dead-link>Dead Link</a>
Before the </body> tag insert the follow script
var deadLinks = document.querySelectorAll(`[data-dead-link]`)
deadLinks.forEach(el => {
el.href = "404-error-page.html"
})

kaltura multiple players on the same page

I am trying to embed more than one players on the same page, but that has no success until now. In order to embed the player we need a unique target_id to target the element of the DOM and then the entry_id of the specific video. This is done in the following function:
function embedPlayer() {
var linkPart = $('#uniqueTarget').data('entry');
var conf = {
"targetId": "uniqueTarget",
"wid": "_1912616",
"uiconf_id": "37591811",
"entry_id": linkPart,
"flashvars": {
"controlBarContainer.plugin": false,
"inlineScript": false
}
};
kWidget.thumbEmbed(conf);
}
Here is the related HTML, which is dynamically created from WordPress every time that the user wants to embed a video:
<div style="width: 100%; display: inline-block; position: relative;">
<div class="theRatio"></div>
<div id="uniqueTarget" data-entry="'+ linkPart +'"
style="position:absolute;top:0;left:0;right:0;bottom:0">
</div>
</div>
Unfortunately if I try to embed a second player on the same page it will only do the API call for the first player and the second(or the rest, if more) will leave me with plain HTML and the call is not being done. There is an article about the issue at https://knowledge.kaltura.com/javascript-api-kaltura-media-players#ManagingMultiplePlayersontheSamePage, but unfortunately my knowledge is limited and I would need some help with it.
Kaltura recommend using thumb embed when you have multiple players on a page - this will embed thumbnails which will play when they are clicked:
Thumb Embed
This method takes the same arguments as the dynamic embed. Thumbnail embed passes the entire configuration to the kWidget.embed when the user "clicks" on the play button. This is the recommended method to use when you need to embed multiple players/entries in the same web page. The syntax for ThumbEmbed is identical to kWidget.embed ( dynamic embed ) except we call "kWidget.thumbEmbed" instead of "kWidget.embed"
There is more information including example Javascript and examples thumbnails here:
http://player.kaltura.com/docs/thumb
Example Javascript from this link (you can also look at the page in a browser debugger to see exactly how they have set it up):
<div id="myEmbedTarget" style="width:400px;height:330px;"></div>
<script src="{{HTML5LibraryURL}}"></script>
<script>
mw.setConfig("EmbedPlayer.DisableContextMenu",true);
kWidget.thumbEmbed({
'targetId': 'myEmbedTarget',
'wid': '_243342',
'uiconf_id' : '12905712',
'entry_id' : '0_uka1msg4',
});
</script>
Create DIV containers for each of your videos - give them unique IDs, then you can target them and create as many videos as you like. Make sure the kWidget script is loaded. Put this script in your page:
function _embedVideo(targetId,wid,uiconf_id,flashvars,entry_id,cb){
kWidget.embed({
targetId: targetId,
wid: wid,
uiconf_id: uiconf_id,
flashvars: flashvars || {},
entry_id: entry_id,
readyCallback: cb
});
}
For each of your videos, load them like so:
_embedVideo('id-of-div-container','wid-here','uiconfid-here',null,'entryid-here',yourCallbackFunc);
This is how I create multiple videos in my pages. Be sure to specify a callback else pass null.

Click all links on page containing string?

I'm trying to add a function to a toolbar Chrome extension I've made. What I'd like it to do is once a navigate to a particular page I'd like be able to push a button on the tool bar and have it "click" all of the links on that page containing harvest.game?user=123456 with 123456 being a different number for all of the links. It could be using jquery or javascript. The only catch is that the script will need to be inserted as an element to the head of the page as cross domain scripting is not allowed so no external references to a js file. I can handle the adding of the element but, I'm having no luck figuring out the actual function.
The elements containing the links all look like this:
<div class="friendWrap linkPanel">
<h5>Christine...</h5>
<div class="friend-icon">
<img src="https://graph.facebook.com/100001726475148/picture"></div>
<div class="levelBlock friend-info">
<p>level</p>
<h3 class="level">8</h3></div>
Harvest
<a class="boxLink" href="profile.game?user_id=701240"><span></span></a></div>
Something like this (I know this is a mess and doesn't work)? OR maybe something BETTER using jquery?
var rlr=1;
function harvestall(){var frt,rm,r,rld,tag,rl;
var frt=1000;
r=document.getElementsByClassName("friendWrap linkPanel");
rl=r.length;
rld=rl-rlr;
if(rld>=0){tag=r[rld].getElementsByTagName('a');
if (rl>=1 {rlr++;harvestall();}
else if (rl>=1) {tag[1].onclick();do something??? ;}
}
Something like this should work
$("a[href*='harvest.game?user=']").trigger("click");
// Using jQuery, wait for DOMReady ...
$(function harvestLinks() {
// Only create regexp once ...
var reURL = /harvest.game\?user=/,
// Create a ref variable for harvest links ...
// Use 'links' later without querying the DOM again.
links = $("a").filter(
function() {
// Only click on links matching the harvest URL ...
return this.href && reURL.test(this.href);
}
).click();
});

Webcomic Navigation Using Javascript?

I'm building my new webcomics home on my website and have ran smack into a wall.
Here's what I want and what I've tried.
I'm trying to have something where using JavaScript I can make only the image of the comic change so that I do not have to make a new page for every single image. I don't mind having to do extra coding work as long as I don't have hundreds of pages in my directory.
I was going to have a /First Next Prev Last/ kind of navigation but I've been so frustrated with it that I kind of scrapped that idea for now and instead am thinking of having a list of the names + link of each comic below the image and just put that into a scroll box. Kinda like how Perry Bible Fellowship works.
I've been trying to figure out if maybe an array is the way to go as I have around 30 images so far and I will be updating daily. Honestly I don't even know if Javascript is the way to go either.
I've also tried to implement [this code](http://interestingwebs.blogspot.com/2012/09/change-image-onclick-with-javascript.html
) to see if it would work and it just seems to break as soon as I try to plug in my own stuff into it. Here's an example of my javascript butcher job:
<script language="javascript">
function Drpepper()
{
document.getElementById("image").src = "/comics/1DrPepper.jpg";
}
function Applestore()
{
document.getElementById("image").src = "/comics/2Applestore.jpg";
}
</script>
<p>
<img alt="Dr Pepper" src="1DrPepper.jpg"
style="height: 85px; width: 198px" id="image" /></p>
<p>
<input id="Button1" type="button" value="Dr Pepper" onclick="DrPepper()"/>
<input id="Button2" type="button" value="Apple Store" onclick="Applestore()" /></p>
Is there anyway to expand this for my purposes? What I would like is to not have buttons and just use links but I can't seem to get beyond this part here where the image doesn't even load and the buttons do nothing.
Also if there is some better way of doing this using any other method other than JavaScript, I'm more than open to it, except the aforementioned making hundreds of pages.
First off, consider using jQuery if you're going to go the Javascript route. Here's an example I mocked up for you:
// set up an array of comic images
var imgs = [
'http://dustinland.com/dlands/dland.sxsw.jpg',
'http://dustinland.com/dlands/dland.hipster.jpg',
'http://dustinland.com/dlands/dland.legalize.marijuana.jpg',
'http://dustinland.com/dlands/dland.TLDR.jpg'
],
// initialize current to 0
current = 0;
// define a function that returns the next item in the imgs array,
// or the first if we're already at the last one
function next() {
current++;
if (current >= imgs.length) current = 0;
return imgs[current];
}
// define a function to do the opposite of next()
function prev() {
current--;
if (current < 0) current = imgs.length - 1;
return imgs[current];
}
// define the first image in terms of a jquery object
var comic = $('<img/>').attr('src', imgs[0]);
// append to DOM
$('#comics').append(comic);
// click the prev button, get the previous image
$('#prev').on('click', function(){
comic.attr('src', prev());
});
// click the next button, get the next image
$('#next').on('click', function(){
comic.attr('src', next());
});
See this in action here: http://jsfiddle.net/QzWV5/
This may work fine for your application, but maybe you should consider the advice of #icktoofay; using Javascript will mean, at the very least, that Google won't automatically crawl all your images. This also presents a usability problem: do you want to force your users to click through every comic in order to reach the first? It's probably best if every image were reachable via its own URL, that way, anyone who came across your comic on the web could easily link to an individual comic.
Have you considered using Tumblr, Blogger, or Wordpress?

Automatically rotate through content

I have 7 graphs that are accessible to me through a web site. I want to develop my own web application that automatically cycles through each of these graphs, so I can display them on a huge monitor.
I want the functionality to be similar to an image carousel but it would be for web pages instead of images. What are my options? A jQuery plugin? AJAX and an iframe? Keep in mind that I want the data to be live while I display it.
You could use javascript, and a Frame with a simple timer to load it.
Nothing complex needed,
In the title frame set add this:
<script language="JavaScript">
var toShow;
var URL = new Array ('http://www.google.com','www.yahoo.com','www.bit.ly');
function setupTimer() {
toShow = 0;
loadNext();
var t=setTimeout("loadNext()", 3000);
}
function loadNext(){
parent.reportframe.location=URL[toShow];
toShow++;
if (toShow>3) toShow = 0;
}
</script>
<body onLoad="setupTimer()">
Then it will keep reloading the frames.
I just wrote this, did not test it, let me know if you need more help.
http://jsfiddle.net/5dazE/5/show
That's a basic slideshow. You can add or remove sites and then press play. It will rotate every 30 seconds. the code can be fond here: http://jsfiddle.net/5dazE/5
it could use more work, but I am in agreement with #nycynik. It is a great idea.

Categories