Soundcloud HTML5 widget continuous play - soundcloud

I'm trying to get the SoundCloud HTML5 player widget to automatically start and seek to a specific track and position but no matter what I try it doesn't work.
I'm using the API code below:
<iframe width="100%" height="450" scrolling="no" id="soundcloud-player" frameborder="no" src="https://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Fplaylists%2F3058825&color=00be53&auto_play=false&show_artwork=true"></iframe>
<script type="text/javascript" src="http://w.soundcloud.com/player/api.js"></script>
<script type="text/javascript">
(function(){
var widgetIframe = document.getElementById('soundcloud-player'),
widget = SC.Widget(widgetIframe);
widget.bind(SC.Widget.Events.READY, function() {
widget.play();
widget.seekTo('5000');
});
widget.bind(SC.Widget.Events.PLAY, function() {
// get information about currently playing sound
widget.getCurrentSound(function(currentSound) {
console.log('sound ' + currentSound.title + 'began to play');
});
}); }());
What I'm basically trying to accomplish is have the player automatically seek to the same spot when the user switches between pages on the site. I plan on reading from a cookie, the position and track and then using the method above. Any help would be greatly appreciated!

The problem is most probably related to the sound not being fully loaded at the moment when you are trying to call seekTo. You can easily verify this by adding the following bit to your code:
// …
widget.bind(SC.Widget.Events.READY, function() {
widget.play();
// Note setTimeout here!
// This will now work since the needed part of the sound
// will have loaded after the timeout
setTimeout(function () {
widget.seekTo('5000');
}, 1000);
});
// …
But since you don't really want to have arbitrary timeout in your code, it's a good idea to attach event handler to progress event:
widget.bind(SC.Widget.Events.LOAD_PROGRESS, function onLoadProgress (e) {
if (e.loadedProgress && e.loadedProgress === 1) {
widget.seekTo(15000); // seek to previous location
widget.unbind(SC.Widget.Events.LOAD_PROGRESS);
}
});
Here's a working version of this code http://jsbin.com/ebeboj/2/edit
Also, in case you have very long tracks, you could also retrieve duration from the sound (via getCurrentSound), check at what point in range from 0 to 1 the track has stopped playing and only wait for that value (since loadedProgress === 1 might take a while), something like:
widget.getCurrentSound(function(currentSound) {
// currrentSound.duration is 269896 for the first track of your playlist
relativePreviousPlay = previousPlay / currentSound.duration; // ~0.204
});
widget.bind(SC.Widget.Events.LOAD_PROGRESS, function onLoadProgress (e) {
if (e.loadedProgress && e.loadedProgress > relativePreviousPlay) {
widget.seekTo(previousPlay); // seek to previous location
widget.unbind(SC.Widget.Events.LOAD_PROGRESS);
}
});
Check out working example for the last bit of code here http://jsbin.com/ebeboj/4/edit
Sidenote: I'd recommend using localStorage over cookies for storing previous position of playback, because cookies will travel back and forth from client to server slowing down your website, and you likely don't need the information on the sever side.

Related

postMessage() event listener not working

I am working with a 3rd party who supplies a URL to be put into an iFrame to display some hosted video playback.
this is cross-domain
they use JWPlayer as their player of choice
I requested a way to 'know' when the video playback is complete. From reading, looks like the postMessage() callback is what many use.. and is what the 3rd vendor suggested, and mentioned they would implement.
I was given a TEST url that has this 'call back' function in it... and to see if I can could use it.
I can not seem to get any alert from the callback/listener functions?
As this is the first time I am implementing this, Im not sure if the error stems from my end or theirs?
I'm thinking it may be the path form the postMessage() function?
After firebugging the code.. I eventually fund their JS/callback set up here:
jwPI.on('complete', function(event){
playbackTime= playbackTime + (jwPI.getPosition() - positionA);
positionA=jwPI.getPosition();
parent.postMessage('EndVideo','*');
});
My side of things has the simple event listener added like so:
window.addEventListener("message", function(evt) {
//do whatever
alert("VIDEO CALLBACK FIRED");
});
My questions are:
1.) Why is this not working? a target/scope issue?
2.) Do I need to have the 3rd party vendor update the path in their postMessage() callback? where does '.parent' actually point to? (if this is an embedded iFrame?) and there are DIV's..etc..etc..etc housing the nested iFrame content?
my listener function is in the main parent file that loads this iFrame?
3.) Can I just leave it as 'as-is' and somehow change the path/target in my listener?
Solution posted:
here is a both a jQuery and JS solution
** note the jQuery approach need to use originalEvent in the scope
//jQuery approach
$(window).on("message onmessage", function(evt) {
//message
var targetData = evt.originalEvent.data;
//origin
var targetOrigin = evt.originalEvent.origin;
//check origin for security and to make Scott proud
if(targetOrigin !== 'https://example.com'){
//no same origin, exploit attempt in process possibly
}
//do whatever
});
//Javascript approach
window.addEventListener("message", function(evt) {
//message
var targetData = evt.data;
//source
var targetSource = evt.source; //iframe source message stems from - doesnt work
//origin
var targetOrigin = evt.origin;
if(targetOrigin !== 'https://example.com'){
//no same origin, exploit attempt in process possibly
}
//do whatever
});
(Posted an answer on behalf of the question author).
Here is a both a jQuery and JS solution. Note the jQuery approach need to use originalEvent in the scope.
//jQuery approach
$(window).on("message onmessage", function(evt) {
//message
var targetData = evt.originalEvent.data;
//origin
var targetOrigin = evt.originalEvent.origin;
//check origin for security and to make Scott proud
if(targetOrigin !== 'https://example.com'){
//no same origin, exploit attempt in process possibly
}
//do whatever
});
//Javascript approach
window.addEventListener("message", function(evt) {
//message
var targetData = evt.data;
//source
var targetSource = evt.source; //iframe source message stems from - doesnt work
//origin
var targetOrigin = evt.origin;
if(targetOrigin !== 'https://example.com'){
//no same origin, exploit attempt in process possibly
}
//do whatever
});

How to wait the page to test is loaded in non angular site?

I've tried this:
browser.wait(function () {
return browser.executeScript('return document.readyState==="complete" &&' +
' jQuery !== undefined && jQuery.active==0;').then(function (text) {
return text === true;
});
}, 30000);
If jQuery.active==0 then page is completely loaded. This should work for sites with JQuery and non angular pages.
However, I have many problems of instability to test for non angular sites.
How to fix this?
By default protractor waits until the page is loaded completely. If you are facing any error then it is because protractor is waiting for the default time to be completed, that you have specified in your conf.js file to wait until page loads. Change the value to wait a for longer time if you think your app is slow -
// How long to wait for a page to load.
getPageTimeout: 10000, //Increase this time to whatever you think is better
You can also increase the defaultTimeoutInterval to make protractor wait a little longer before the test fails -
jasmineNodeOpts: {
// Default time to wait in ms before a test fails.
defaultTimeoutInterval: 30000
},
If you want to wait for any particular element, then you can do so by using wait() function. Probably waiting for last element to load is the best way to test it. Here's how -
var EC = protractor.ExpectedConditions;
var lastElement = element(LOCATOR_OF_LAST_ELEMENT);
browser.wait(EC.visibilityOf(lastElement), 10000).then(function(){ //Alternatively change the visibilityOf to presenceOf to check for the element's presence only
//Perform operation on the last element
});
Hope it helps.
I use ExpectedConditions to wait for, and verify page loads. I walk through it a bit on my site, and example code on GitHub. Here's the gist...
Base Page: (gets extended by all page objects)
// wait for & verify correct page is loaded
this.at = function() {
var that = this;
return browser.wait(function() {
// call the page's pageLoaded method
return that.pageLoaded();
}, 5000);
};
// navigate to a page
this.to = function() {
browser.get(this.url, 5000);
// wait and verify we're on the expected page
return this.at();
};
...
Page Object:
var QsHomePage = function() {
this.url = 'http://qualityshepherd.com';
// pageLoaded uses Expected Conditions `and()`, that allows us to use
// any number of functions to wait for, and test we're on a given page
this.pageLoaded = this.and(
this.hasText($('h1.site-title'), 'Quality Shepherd')
...
};
QsHomePage.prototype = basePage; // extend basePage
module.exports = new QsHomePage();
The page object may contain a url (if direct access is possible), and a pageLoaded property that returns the ExepectedCondition function that we use to prove the page is loaded (and the right page).
Usage:
describe('Quality Shepherd blog', function() {
beforeEach(function() {
// go to page
qsHomePage.to();
});
it('home link should navigate home', function() {
qsHomePage.homeLink.click();
// wait and verify we're on expected page
expect(qsHomePage.at()).toBe(true);
});
});
Calling at() calls the ExpectedCondidion (which can be be an and() or an or(), etc...).
Hope this helps...

Is it possible to redirect the user to Firefox browser

My current code pops up a warning box window telling the user that he or she is using IE. But is there a way to direct them to Firefox website?
public static boolean isIEBrowser()
{
return (Window.Navigator.getUserAgent().toUpperCase().indexOf("TRIDENT") != -1);
}
if (isIEBrowser())
{
SC.warn("It looks like you're using a version of Internet Explorer." +
" For the best GUI experience, please update your browser.");
}
Sure!
This might be more of what you're looking for.
String site = "http://www.mozilla.org/en-US/firefox/new/";
Window.Location.assign(site);
Window.Location.reload();
You can also add a simple timer that redirects them after a certain number of seconds or a button that takes them directly to the site.
edit:
Or... you can do this in pure javascript
JS:
function changeURL(site) {
window.location.href = site;
}
HTML:
<script>
changeURL('http://www.mozilla.org/en-US/firefox/new/');
</script>

With HTML5 SoundCloud player widget how do you programmatically skip to a different track without causing second unwanted track from playing?

I am using the HTML5 Soundcloud widget API to skip to another song on the sound finish event.
http://jsbin.com/axuzoj/4/edit
Unfortunately there appears to be a race condition bug in the finish event. The Soundcloud player ends up playing two songs simultaneously: the next song in the list and the song that was skipped to in the finish event handler.
var widget = null;
$(function() {
var iframe = document.querySelector('#soundcloud_player iframe');
widget = SC.Widget(iframe);
widget.bind(SC.Widget.Events.READY, function() {
widget.bind(SC.Widget.Events.FINISH, function() {
widget.skip(3);
});
});
});
Is this a known bug?
Is there a better way to skip to a different track after a sound finishes?
Is there a way to turn off continuous play?
Adding a short wait before skipping in the finish event handler, gets around the problem. But doesn't seem like a good method.
window.setTimeout(function() { widget.skip(3); }, 300);
Another work around is to skip to a song just before the previous song finishes, using PLAY_PROGRESS event instead of on FINISH event.
widget.bind(SC.Widget.Events.READY, function() {
widget.bind(SC.Widget.Events.PLAY_PROGRESS, function(obj) {
if (obj.relativePosition > 0.999) {
widget.pause();
widget.skip(3);
}
});
});
Yes, there was a race-condition bug which is fixed now.

Mobile Safari: Disable scrolling pages "out of screen"

I want to block scrolling page "out of the iPhone screen" (when gray Safari's background behind the page border is visible). To do this, I'm cancelling touchmove event:
// Disables scrolling the page out of the screen.
function DisableTouchScrolling()
{
document.addEventListener("touchmove", function TouchHandler(e) { e.preventDefault(); }, true);
}
Unfortunately, this also disables mousemove event: when I tap on a button then move my finger out of it, then release the screen, the button's onclick event is triggered anyway.
I've tried mapping touch events on mouse events, as desribed here: http://ross.posterous.com/2008/08/19/iphone-touch-events-in-javascript/, but to no avail (the same behavior).
Any ideas?
From what I understand of your question, you've attempted to combine the code you've presented above with the code snippet provided by Ross Boucher on Posterous. Attempting to combine these two snippets back-to-back won't work, because in disabling touchmove, you've also disabled the shim that allows mousemove to work via his sample.
This question and its answers sketch out a workable solution to your problem. You should try these two snippets to see if they resolve your issue:
This snippet, which disables the old scrolling behavior:
elementYouWantToScroll.ontouchmove = function(e) {
e.stopPropagation();
};
Or this one, from the same:
document.ontouchmove = function(e) {
var target = e.currentTarget;
while(target) {
if(checkIfElementShouldScroll(target))
return;
target = target.parentNode;
}
e.preventDefault();
};
Then, drop in the code on Posterous:
function touchHandler(event)
{
var touches = event.changedTouches,
first = touches[0],
type = "";
switch(event.type)
{
case "touchstart": type = "mousedown"; break;
case "touchmove": type="mousemove"; break;
case "touchend": type="mouseup"; break;
default: return;
}
//initMouseEvent(type, canBubble, cancelable, view, clickCount,
// screenX, screenY, clientX, clientY, ctrlKey,
// altKey, shiftKey, metaKey, button, relatedTarget);
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1,
first.screenX, first.screenY,
first.clientX, first.clientY, false,
false, false, false, 0/*left*/, null);
first.target.dispatchEvent(simulatedEvent);
event.preventDefault();
}
And that should do it for you. If it doesn't, something else isn't working with Mobile Safari.
Unfortunately I haven't had the time to check out to above yet but was working on an identical problem and found that the nesting of elements in the DOM and which relation you apply it to affects the handler a lot (guess the above solves that, too - 'var target = e.currentTarget').
I used a slightly different approach (I'd love feedback on) by basically using a class "locked" that I assign to every element which (including all its children) i don't want the site to scroll when someone touchmoves on it.
E.g. in HTML:
<header class="locked">...</header>
<div id="content">...</div>
<footer class="locked"></div>
Then I have an event-listener running on that class (excuse my lazy jquery-selector):
$('.ubq_locked').on('touchmove', function(e) {
e.preventDefault();
});
This works pretty well for me on iOs and Android and at least gives me the control to not attach the listener to an element which I know causes problems. You do need to watch your z-index values by the way.
Plus I only attach the listener if it is a touch-device, e.g. like this:
function has_touch() {
var isTouchPad = (/hp-tablet/gi).test(navigator.appVersion);
return 'ontouchstart' in window && !isTouchPad;
}
This way non-touch devices will not be affected.
If you don't want to spam your HTML you could of course just write the selectors into an array and run through those ontouchmove, but I would expect that to be more costly in terms of performance (my knowledge there is limited though). Hope this can help.