Souncloud soundmanager multiple playlist - soundcloud

Hi i'm using SoundCloud manager, http://www.schillmania.com/projects/soundmanager2/ to play audio files on my website. Following their documentation over here: http://soundcloud-sm2.heroku.com/docs/application.html , i'm able to play a sound cloud playist from a set url.
Now I have multiple sets/ playlist, how can I instantiate a new sound manager class and toggle between them by hidden their elements using css.
Here is the sound manager application code( ideally I would want to create two soundmanager.Createsound())
var consumer_key = "59f0360dads135bd07sdasasdadsad8acc14ae2d929",
url = "https://soundcloud.com/artist-2/sets/owl";
// Resolve the given url and get the full JSON-worth of data from SoundCloud regarding the playlist and the tracks within.
$.getJSON('http://api.soundcloud.com/resolve?url=' + url + '&format=json&consumer_key=' + consumer_key + '&callback=?', function(playlist){
// I like to fill out the player by passing some of the data from the first track.
// In this case, you'll just want to pass the first track's title.
$('.title').text(playlist.tracks[0].title);
// Loop through each of the tracks
$.each(playlist.tracks, function(index, track) {
// Create a list item for each track and associate the track *data* with it.
$('<li>' + track.title + '</li>').data('track', track).appendTo('.tracks');
// * Get appropriate stream url depending on whether the playlist is private or public.
// * If the track includes a *secret_token* add a '&' to the url, else add a '?'.
// * Finally, append the consumer key and you'll have a working stream url.
url = track.stream_url;
(url.indexOf("secret_token") == -1) ? url = url + '?' : url = url + '&';
url = url + 'consumer_key=' + consumer_key;
// ## SoundManager2
// **Create the sound using SoundManager2**
soundManager.createSound({
// Give the sound an id and the SoundCloud stream url we created above.
id: 'track_' + track.id,
url: url,
// On play & resume add a *playing* class to the main player div.
// This will be used in the stylesheet to hide/show the play/pause buttons depending on state.
onplay: function() {
$('.player').addClass('playing');
$('.title').text(track.title);
},
onresume: function() {
$('.player').addClass('playing');
},
// On pause, remove the *playing* class from the main player div.
onpause: function() {
$('.player').removeClass('playing');
},
// When a track finished, call the Next Track function. (Declared at the bottom of this file).
onfinish: function() {
nextTrack();
}
});
});
});

Related

Infinite Scroll history breaks the URL when using JSON

I'm using the Infinite Scroll plugin for my products listings. The plugin is loading the data from a JSON and it's working fine if I don't enable the history.
Now I would like the plugin to change the history, so when the user opens a product detail page and then uses the back button he / she gets redirected to the last scroll position.
A problem occurs when I enable the history: 'replace' option that changes the page URL for the subfolder and path of my server-side script breaking all links and images.
Here is my init code:
$infiniteContainer = $('#resultsContainer').infiniteScroll({
path: function() {
return 'ajax/ajax.items.php?'
+ '&s=' + searchStr
+ '&cat=' + filterCat
+ '&sub=' + filterSubCat
+ '&order=' + orderBy
+ '&offset=' + this.pageIndex;
},
responseType: 'text',
history: 'replace',
loadOnScroll: true,
checkLastPage: true
});
when I enable the history then my URL gets converted to:
mydomain.com/ajax/ajax.items.php?s=&cat=&sub=&order=&offset=1
and the URL should stay as mydomain.com/
How can I prevent infinite scroll to change the URL to the wrong path and just passing the variables I need for scrolling to a specific page?
When a new page is loaded from a URL specified by the path function, that URL replaces the current URL displayed in the address bar.
This is done in the setHistory function of the infinite-scroller (see line 1159 in infinite-scroll.pkgd.js).
If your goal is to load data from mydomain.com/ajax/ajax.items.php?s=&cat=&sub=&order=&offset=1 but have mydomain.com?s=&cat=&sub=&order=&offset=1 displayed in the address bar instead, you can modify that function.I didn't find a way to configure behaviour of setHistory, so the following workaround replaces it (for the single InfiniteScroll instance infScroll):
const infScroll = new InfiniteScroll( '#resultsContainer', path: function() {
return 'ajax/ajax.items.php?'
+ '&s=' + searchStr
+ '&cat=' + filterCat
+ '&sub=' + filterSubCat
+ '&order=' + orderBy
+ '&offset=' + this.pageIndex;
},
responseType: 'text',
history: 'replace',
loadOnScroll: true,
checkLastPage: true
});
const originalSetHistory = infScroll.setHistory;
infScroll.setHistory = function (title, path) {
const modifiedPath = path.replace("mydomain.com/ajax/ajax.items.php", "mydomain.com")
originalSetHistory.call(infScroll, originalSetHistory, modifiedPath);
}

Soundcloud: How do I know the sound cloud track ID right away after uploading a track?

http://developers.soundcloud.com/docs/api
When I look at the API docs, I see
SC.stream("/tracks/293", function(sound){
sound.play();
});
When I look at the track I uploaded, it only provides me the permalink. How do I get the track ID from the website? Do I always have to do a /resolve to get the ID?
This is probably more manual steps than /resolve, but it is "from the website." The sound id also appears in the embed code when you go to the sound and click "Share".
For example, if you go to a sound page, e.g.:
https://soundcloud.com/lowcountrykingdom/another-ordinary-day
Then click "Share", which brings up a pop up. Click "Embed" to switch to the embed tab, and copy the Embed code, which will look something like:
<iframe width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/47580057&color=ff6600&auto_play=false&show_artwork=true"></iframe>
Note the ID in the value of the url query parameter:
url=https%3A//api.soundcloud.com/tracks/47580057
I'd use jquery ajax call to grab the data from Soundcloud. Say you save your variables permalink_url and client_id:
$.get('http://api.soundcloud.com/resolve.json?url='+
permalink_url+'/tracks&client_id='+client_id , function (result) {
console.log(result);
});
This should log an array of the songs. Check out this bin for reference http://jsbin.com/viviza/4/edit
Update: This answer is pretty old.
Soundclick docs https://developers.soundcloud.com/docs/api#uploading
The SC object now allows for getting the id's directly
SC.connect().then(function(){
return SC.get('/me/tracks');
}).then(function(tracks){
return tracks.map(function(track){
console.log("you can log the id here too: " + track.id")
return track.id
})
})
You could also get all the tracks from a given user id. Then use $.map() to place each of the tracks into an array. Call SC.stream() with song[i].id to play a random song from the array from the array of tracks.
SC.get('/users/123456/tracks/', function(tracks) {
// get an array of tracks
var song = $.map(tracks, function(i){
return i;
});
var i = Math.floor(Math.random() * song.length) // get a random value between 0 & the of songs in SC account -1
SC.stream(song[i].id, function(sound){
sound.play();
});
});
Using JavaScript to find the track data from a soundcloud song url:
let trackUrl = 'https://soundcloud.com/user-869590724/talk-to-animals-sentra-remix'
let client_id = '<your-client-id>'
let resolveUrl = `http://api.soundcloud.com/resolve.json?url=${trackUrl}/tracks&client_id=${client_id}`
fetch(resolveUrl, {
method: 'get'
}).then((response) => {
return response.json()
}).then((result) => {
/* now you have the track */
console.log(result)
})

With SoundCloud default audio widget can you set it to shuffle from JavaScript?

I am using the default SoundCloud audio widget to play a playlist and would like the songs to play in a random order. I am using the SoundCloud JavaScript SDK oEmbed object (the iframe version).
<script src="//connect.soundcloud.com/sdk.js"></script>
SC.oEmbed("//soundcloud.com/buzzinfly", {
auto_play: true,
start_track: random_start_track,
iframe: true,
maxwidth: 480,
enable_api: true,
randomize: true
},
document.getElementById("soundcloud_player"));
The documentation doesn't mention any randomize or shuffle attribute, but other undocumented attributes like start_track are supported with oembed.
//developers.soundcloud.com/docs/oembed#parameters
//developers.soundcloud.com/docs/widget
Does any one know if there is an attribute to shuffle the song order in the default audio widget?
If not, is there is a way to capture events from the default SoundCloud widget, so I can play a random song after a song finish event? Like you can with the custom player.
//developers.soundcloud.com/docs/custom-player#events
$(document).bind('onPlayerTrackSwitch.scPlayer', function(event, track){
// goto random track
});
Thanks
Update
Here is code am I using after getting gryzzly's help.
The next button works great. I can skip thru random songs. Unfortunately, when a track finishes playing, I hear the audio of two songs: the next song in the playlist and the random track that is skipped to in the FINISH event.
var widget = null;
var song_indexes = new Array();
var current_index = 0;
$(function() {
var iframe = document.querySelector('#soundcloud_player iframe');
widget = SC.Widget(iframe);
widget.bind(SC.Widget.Events.READY, function() {
widget.unbind(SC.Widget.Events.FINISH);
widget.bind(SC.Widget.Events.FINISH, function() {
play_next_shuffled_song();
});
widget.getSounds(function(sounds) {
create_shuffled_indexes(sounds.length);
play_next_shuffled_song();
});
});
$("#button_sc_next").on("click", play_next_shuffled_song);
});
function play_next_shuffled_song() {
current_index++;
if (current_index >= song_indexes.length) {
current_index = 0;
}
var track_number = song_indexes[current_index];
widget.skip(track_number);
}
function create_shuffled_indexes (num_songs) {
for (var i=0;i<num_songs;i++) {
song_indexes.push(i);
}
song_indexes = shuffle(song_indexes);
}
//+ Jonas Raoni Soares Silva
//# http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o){ //v1.0
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
You can find the documentation for Widget API here.
Pseudo code for this would be something like:
load widget
get widget sounds LENGTH /* say 5 */
create an ARRAY of that LENGTH and shuffle it /* to have something like [3, 1, 0, 2, 4] */
create function SKIP that will check if ARRAY still has any items in it (length is not 0) and skip player to array.pop() index /* pop will return the last item in the array and return its value */
attach event handler to FINISH events that will run SKIP function
run SKIP function first time yourself
If user skips with the “next” control in widget's UI the widget will
just play next song in the list. You could perhaps detect that
somehow and skip to another random track.
I hope this helps!

Jquery in Custom HTML Helper Extensions to pick value from the form

I have used this custom Helper in My Razor View.
#Html.Link("OpenewWindow", Constants.Value, new { k = Constants.k, Staff_ID = LoginHelper.GetLoggedInUser() }, new { id = "mytag", target="_blank" })
When I Click on this link it opens me a new window with the Querystrings ConstantValue/Constants?=someValue&Staff_ID=UserLoggedName.
I want to pick the radio button selected value on the form and pass the checked value in QueryString.
So where can I use Jquery function in my custom Helper method to pick the value from the form.
The Custom Helper method takes this kind of aurguments.
public static IHtmlString Link(this HtmlHelper htmlHelper, string linkText, string baseUrl, object query, object htmlAttributes).
You could use javascript to do that. For example you could subscribe to the click event of the link and then open a popup window by appending the new query string parameter:
$(function() {
$('#id_of_link').click(function() {
var url = this.href;
if (url.indexOf('?') > -1) {
url += '&';
} else {
url += '?';
}
// get the value of the radio button
var value = $(':radio[name="name_of_your_radio_groups"]:checked').val();
url += url + 'radiovalue=' + encodeURIComponent(value);
window.open(url, 'newwindow');
// cancel the default action
return false;
});
});
If you don't need to use javascript then a cleaner approach is to use a form instead of a link. This way the value of the selected radio button will automatically be sent.

Re-POST-ing a form using Ajax, for back/fwd history, in jQuery Mobile

I'm investigating the suitability of the jQM history management for my organization's mobile web site. Part of our requirement is that when a user posts a form, it posts using Ajax. When a user taps "back" and then "forward" browser buttons, we need to re-post the form using Ajax again. Here's a diagram:
[home.php: post to new.php] =>
[new.php: post to list.php] =>
[from list.php, click back twice to home.php] =>
[* home.php: click fwd, does a GET request to new.php *] =>
[* new.php: click fwd, does a GET request to list.php *]
[*] not the behavior I want. I want to re-POST data from steps 1 and 2
During steps 4 and 5, I want to intercept the jQM execution at the "pagebeforeload" event (seems like the right place), and modify the data.options.data (to include the serialized post data) and data.options.type (to POST) properties of the data object which is passed to the event handler. Then I'd let the pageload process move on with the modified values. This, I think, would give me the behavior I want.
So far, I see that I can intercept the pagebeforeload event and modify the values with the below event handler:
$(document).bind("pagebeforeload",
function( e, data ) {
console.log(data.toPage);
console.log(data.options);
data.options.type = "POST";
data.options.data = "edit=Hanford";
}
);
But the missing piece is, how can I "store" the information in steps 1 and 2, such that when I intercept the pagebeforeload event in 4 and 5, I can know to modify the "type" and "data" properties properly.
I've made a jquery/browser History prototype to illustrate the behavior I would like to get from jQuery Mobile. The JavaScript is:
$(window).load(function() {
//listen to the history popstate event
$(window).bind('popstate',
function(e) {
if (e.originalEvent.state && e.originalEvent.state.type && e.originalEvent.state.type == "post") {
//do an ajax post based on what is stored in history state
$.post(e.originalEvent.state.path,
e.originalEvent.state.data,
function(data) {jaxer(data,'POST')});
} else if (e.originalEvent.state !== undefined){
//do an ajax get
$.get(location.pathname,
function(data) {jaxer(data,'GET')});
}
});
//add event listeners
addClickHandler();
});
function jaxer(data, msg) {
if (msg) {console.log(msg+' request made using ajax');}
$('#slider')[0].innerHTML = data;
addClickHandler();
}
//hijax hyperlinks and form submissions
function addClickHandler() {
$('a').click(function(e) {
history.pushState({
path: this.path
},
'', this.href);
$.get(this.href,
function(data) {jaxer(data,'GET')});
e.preventDefault()
});
$('form').submit(function(e) {
var formData = $(this).serialize();
console.log('saving serialized form data into historyState: '+formData);
history.pushState({path: this.action, data: formData, type: "post"},'',this.action);
$.post(this.action,
$(this).serialize(),
function(data) {jaxer(data,'POST')});
e.preventDefault();
});
//add the form submit button to the form as a hidden input such that it will get serialized
$('form input[type="submit"]').click(function() {
$(this.form).append("<input type='hidden' name='" + this.name + "' value='" + this.value + "'/>");
});
console.log("event handlers added to DOM");
};
When a user-initiated POST occurs, I put the serialized POST data into the history's state object. Then, when a popstate event occurs, I can query the state object for this information. If I find it, then I can perform an ajax POST. I would like to get the same functionality within the jQuery Mobile history handling. That way I can take advantage of the page change animations, etc.