I want to know when the audio is still playing , and when it stopped to perform other actions . None of these options works for me. I tried for reproduce a same file, but only if is stopped, I try for a few days, but it still not work
function reproducirAudio(ruta) {
var ruta = "/android_asset/www/sounds/button-1.mp3";
$scope.media2 = new Media(ruta, function () {
$scope.media2.play();
}, function (b) {
}, function (a) {
alert(JSON.stringify(a));
});
}
function reproducirAudio(ruta) {
var ruta = "/android_asset/www/sounds/button-1.mp3";
$scope.media2 = new Media(ruta, bien,mal,status);
function bien(){ $scope.media2.play();}
function mal(){}
function status(estatus){ console.log("status")}
}
function reproducirAudio(ruta) {
var ruta = "/android_asset/www/sounds/button-1.mp3";
$scope.media2 = new Media(ruta, bien,mal,status);
function bien(){ $scope.media2.play();}
function mal(){}
function status(estatus){ alert(status)}
}
function reproducirAudio(ruta) {
var ruta = "/android_asset/www/sounds/button-1.mp3";
$scope.media2 = new Media(ruta, bien,mal,getStatusMessage);
function bien(){ $scope.media2.play();}
function mal(){}
function getStatusMessage(status){
if(status === 0){console.log('Media.MEDIA_NONE');}
else if(status === 1){console.log('Media.MEDIA_STARTING');}
else if(status === 2){console.log('Media.MEDIA_RUNNING');}
else if(status === 3){console.log('Media.MEDIA_PAUSED');}
else if(status === 4){console.log('Media.MEDIA_STOPPED');}
}
}
I have done this by creating a blank media player, then later setting the media. To test if it is playing just perform a check that tests if your media player is null or undefined.
$scope.media;
$scope.media = new Media("some/media/path.mp3);
if ($scope.media != null) {
someAction();
}
else {
otherAction();
}
Another option is to test if the media length is greater than 0.
$scope.media.getCurrentPosition(
//success
function (position) {
if (position > 0) {
console.log("A song is playing!");
}
},
// error
function () {
console.log("An error occured!");
}
);
finally it worked . I put this code and i realize a downgrade to cordova-media-plugin to 1.0.1 version
function reproducirAudioPorBoton(ruta) {
var audiofile = new Media('file:///android_asset/www/sounds/M.mp3');
audiofile.play();
var counter=0;
var timerDur = setInterval(function() {
counter = counter + 100;
if (counter > 2000) {
clearInterval(timerDur);
}
var dur = audiofile.getDuration();
if (dur > 0) {
clearInterval(timerDur);
console.log(dur + " sec");
}
}, 100);
}
I am using google maps and i am trying to put a pause in execution to prevent QUERY_LIMIT usage issue. My function that plots the addresses looks like this.
The code works, however i want to try setTimeout or setInterval to see if its going to look better on UI.
How do i call it, what should be the first argument?
Thanx alot.
vLocations = [];
for (var i = 0; i < vAddresses.length; i++) {
//pause to prevent OVER_QUERY_LIMIT issue
//geocode "free" usage limit is 5 requests per second
//setTimeout(PlotAddressesAsUnAssigned, 1000);
//sleep(500);
//this will resolve the address and store it in vLocations
AddWaypointAndUnassigned(vAddresses[i]);
var z = i % 4;
if (z==0 && i != 0) {
//sleep after every 5th geocode call
//alert('going to sleep...i: ' + i);
//sleep(3000);
}
}
Doing a pause (asynchronous execution) inside a loop (synchronous) will usually result in a lot of trouble.
You can use recursive calls that are done only when a timeout ends.
var vLocations = [];
// Manages the timeout and recursive calls
function AddWaypointAndUnassignedWithPause(index){
setTimeout(function(){
// When the timeout expires, we process the data, and start the next timeout
AddWaypointAndUnassigned(vAddresses[index]);
// Some other code you want to execute
var z = i % 4;
if (z==0 && i != 0) {
//sleep after every 5th geocode call
//alert('going to sleep...i: ' + i);
//sleep(3000);
}
if(index < vAddresses.length-1)
AddWaypointAndUnassignedWithPause(++index);
}, 1000);
}
// Start the loop
AddWaypointAndUnassignedWithPause(0);
JSFiddle example.
Try this, hope this will help
vLocations = [];
for (var i = 0; i < vAddresses.length; i++) {
//pause to prevent OVER_QUERY_LIMIT issue
setTimeout(function(){
//this will resolve the address and store it in vLocations
AddWaypointAndUnassigned(vAddresses[i]);
}, 500);
var z = i % 4;
if (z==0 && i != 0) {
//sleep after every 5th geocode call
//alert('going to sleep...i: ' + i);
//sleep(3000);
}
}
What about a waiting line, thats fired when an item is added and stopped when there are no items left.
With setTimeout:
var INTERVAL = 1000 / 5;
var to = null;
var vLocations = [];
function addAddress(vAddress) {
vLocations.push(vAddress);
startTimeout();
}
function startTimeout() {
if( to === null ) {
to = setTimout(processLocation, INTERVAL);
}
}
function processLocation() {
if( vLocations.length ) {
var vAddress = vLocations.shift();
AddWaypointAndUnassigned(vAddress);
to = setTimout(processLocation, INTERVAL);
} else {
to = null;
}
}
With setInterval:
var INTERVAL = 1000 / 5;
var to = null;
var vLocations = [];
function addAddress(vAddress) {
vLocations.push(vAddress);
startInterval();
}
function startInterval() {
if( to === null ) {
to = setInterval(processLocation, INTERVAL);
}
}
function processLocation(cb) {
if( vLocations.length ) {
var vAddress = vLocations.shift();
AddWaypointAndUnassigned(vAddress);
} else
clearInterval(to);
to = null;
}
}
So, I've searched for this high and low and maybe I'm just having trouble understanding jQuery's deferred function or I'm completely on the wrong track. So any help would be appreciated folks!
I basically have a custom jQuery function messager that displays a message with a fadeOut and fadeIn.
(function ( $ ) {
$.fn.messager = function(message, effect, speed) {
$(this).fadeOut(speed).delay(speed).text(message).fadeIn(speed);
return this;
};
}( jQuery ));
So, I have a div called $elem and when $elem.messager gets called multiple times (with different messages), I would like the messager function to wait till its last call has finished. As in the last FadeIn has finished. Because currently what's happening is that the second call of the function is overwriting the animation effect of the first call of the function.
Any ideas?
jQuery Deferred Way
jQuery Deferred object (roughly compromising CommonJS Promises API) can help us managing queued operations. Here is my implementation of queuing messages. You can pass through multiple messages as an array in one call, or synchronize different message boards easily because #messager() returns jQuery object itself but also wrapped as a promise object which will be resolved just when message(s) being displayed.
(function ($) {
function awaits($el) {
var awaits = $el.data('_awaits');
awaits || $el.data('_awaits', awaits = []);
return awaits;
}
function resolveNext(curr /*, ignored */) {
var head = awaits(this).shift();
if (head === curr) {
resolveNext.call(this, 'not await');
} else {
head && head.resolve();
}
}
function display(message, speed) {
var $self = this, await = $.Deferred(), willDone = $.Deferred();
awaits($self).push(await) > 1 || await.resolve();
await.done(function() {
function reveal() {
$self.text(message).fadeIn(speed, function() {
resolveNext.call($self, await);
willDone.resolve();
});
}
$self.fadeOut(speed/2, reveal);
});
return willDone.promise(this);
};
$.fn.messager = function(message, speed) {
speed = speed || 500;
if ($.isArray(message)) {
var arr = [];
message.forEach(function(m) {
arr.push(display.call(this, m, speed));
}, this);
return $.when.apply(this, arr);
} else {
return display.call(this, message, speed);
}
}
}( jQuery ));
function play() {
$('#msgbox1').messager(['A demo of', 'queued messages'], 1000);
for (var i = 3; i > 0; i--) $('#msgbox1').messager(i);
$('#msgbox1').messager(['Ready to sing...', 'Singing...']);
for (var i = 8; i > 0; i--) $('#msgbox2').messager('***');
for (i = 1; i < 8; i++) $('#msgbox2').messager(String.fromCharCode(64 + i));
$('#msgbox2')
.messager('')
.done(function() {
$('#msgbox1')
.messager(['End of demo.', 'Thank you.', 'Run again?'], 1000)
.done(function() {
$('#msgbox1, #msgbox2').one('click', play);
$('#msgbox2').messager('>');
});
});
}
play();
html {
background: rgba(0, 0, 0, 0.25);
}
#msgbox1, #msgbox2 {
color: #FFF;
padding: 0.3em 0.5em;
font-size: 36pt;
text-align: center;
height: 1.8em;
cursor: default;
}
#msgbox2 {
color: yellow;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Queuing Messages with jQuery Deferred Object</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="msgbox1"></div>
<div id="msgbox2"></div>
</body>
</html>
Edit, Updated
Try
(function ($) {
$.fn.messager = messager;
function messager(message, speed, callback) {
var that = $(this);
if (that.data("queue") === undefined) {
$.fx.interval = 0;
that.data("queue", []);
that.data("msg", []);
};
var q = that.data("queue"),
msgs = that.data("msg");
q.push([message, speed, callback]);
msgs.push(message);
var fn = function (m, s, cb) {
return that.fadeOut(s, function () {
that.text(m)
})
.delay(s)
.fadeIn(s, cb)
.promise("fx")
.done(function (el) {
console.log("callback", q.length);
if (q.length > 1) {
q.splice(0, 1);
fn.apply(el, q[0])
} else {
el.data("queue", []);
console.log("done", el.data("queue").length);
always(promise, ["complete", msgs])
.then(complete);
}
return el.promise("fx");
})
}
, promise = $.when(!that.queue("fx").length
? fn.apply(that, q[0])
: that.promise("fx"))
, always = function (elem, args) {
if (elem.state() === "pending") {
console.log(elem.state(), args)
} else {
if (elem.state() === "resolved") {
elem.done(function (elem) {
console.log(msgs.length + " messages complete");
})
};
};
return elem.promise("fx")
};
always(promise, ["start", message, q.length]);
return that
};
}(jQuery));
See .promise()
(function ($) {
$.fn.messager = messager;
function messager(message, speed, callback) {
var that = $(this);
if (that.data("queue") === undefined) {
$.fx.interval = 0;
that.data("queue", []);
that.data("msg", []);
};
var q = that.data("queue"),
msgs = that.data("msg");
q.push([message, speed, callback]);
msgs.push(message);
var fn = function (m, s, cb) {
return that.fadeOut(s, function () {
that.text(m)
})
.delay(s)
.fadeIn(s, cb)
.promise("fx")
.done(function (el) {
console.log("callback", q.length);
if (q.length > 1) {
q.splice(0, 1);
fn.apply(el, q[0])
} else {
el.data("queue", []);
console.log("done", el.data("queue").length);
always(promise, ["complete", msgs])
.then(complete);
}
return el.promise("fx");
})
}
, promise = $.when(!that.queue("fx").length
? fn.apply(that, q[0])
: that.promise("fx"))
, always = function (elem, args) {
if (elem.state() === "pending") {
console.log(elem.state(), args)
} else {
if (elem.state() === "resolved") {
elem.done(function (elem) {
console.log(msgs.length + " messages complete");
})
};
};
return elem.promise("fx")
};
always(promise, ["start", message, q.length]);
return that
};
}(jQuery));
var complete = function() {
if (!$("pre").is("*")) {
$("body").append("<pre>" + JSON.stringify($(this).data("msg"), null, 4))
} else {
$("pre")
.text(JSON.stringify($(this).data("msg"), null, 4));
$("label[for=messages]").text("messages updated")
.show(0).delay(350).hide(0)
};
};
var fx = function() {
$(this).css("color", "purple").animate({
fontSize: "72"
}, 100, function() {
$(this).animate({
fontSize: "36"
}, 100, function() {
$(this).css("color", "inherit")
})
})
};
var input = $("input");
var $elem = $("#messages");
$elem.messager("0", 1000)
.messager("1", 100)
.messager("2", 200)
.messager("3", 300)
.messager("4", 400)
.messager("5", 500)
.messager("6", 600)
.messager("7", 700)
.messager("8", 800)
.messager("9", 900);
$.each("abcdefghijklmnopqrstuvwxyz".split(""), function(key, val) {
$elem.messager(val, 200, fx);
});
$("button").on("click", function() {
$elem.messager(input.val().length > 0 ? input.val() : $.now(), 200);
input.val("")
});
#messages {
display:block;
height:38px;
font-size:36px;
position : absolute;
}
label[for=messages] {
color:blue;
}
pre {
position:relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="button">add messages</label> <label for="messages"></label><br>
<input type="text" /><button>click</button>
<br />
<div id="messages">messages</div>
<br><br>
<script>
(function ( $ ) {
$.fn.messager = function(message, effect, speed, gothru) {
if (!$(this).data('message'))
{
$(this).data('message', Array());
}
$(this).data('message').push({messageContent: message, messageEffect: effect, messageSpeed: speed});
if ($(this).data('message').length > 1 && gothru != true)
{
return;
}
$(this).fadeOut(speed).delay(speed).text(message).fadeIn(speed, function(){
$(this).data("message").shift();
if ($(this).data('message').length > 0)
{
var arrMessage = $(this).data('message');
var messageContent = arrMessage[0].messageContent;
var messageEffect= arrMessage[0].messageEffect;
var messageSpeed= arrMessage[0].messageSpeed;
$(this).data("message").shift();
$(this).messager(messageContent , messageEffect, messageSpeed, true);
}
});
return this;
};
}( jQuery ));
</script>
It's good now.
The naive way of doing it recursively:
Make a global variable(boolean), in this case called queue. If queue is false, set it to true and begin executing the code you want to run. When that code finishes, set queue back to false. Otherwise, if queue was true, just recursively call _this.messager() until queue is set back to false, which would mean that the code is finished running.
fadeIn() and fadeOut() can take callbacks as the final argument, so I'm utilizing that here.
HTML:
<div id="messageBox"></div>
javaScript:
(function ( $ ) {
var queue = false;
$.fn.messager = function(message, effect, speed) {
var _this = $(this);
if (!queue) {
queue = true;
_this.fadeOut(speed, function() {
_this.text(message);
_this.fadeIn(speed, function() {
queue = false;
});
});
} else {
_this.messager(message, effect, speed);
}
return this;
};
}( jQuery ));
$('#messageBox').messager('One', 300);
$('#messageBox').messager('Two', 300);
$('#messageBox').messager('Three', 300);
This typically results in:
Uncaught RangeError: Maximum call stack size exceeded
A more advanced example:
Here we create a second variable called counter to keep track of how many times 'messager' is called recursively and doesn't exceed the limit specified in the options. I set a default of 50, which can be overwritten by the options parameter.
In addition, we've separated out the code that you want to run. This could even be multiple functions that call each other, the important bit is making sure that when your code is finished running, you set queue to false rather than returning false and setting queue to the result of the function. Setting it to the result of the function just makes it undefined until the function finishes returning. We want it to remain as true until the code is finished executing.
This example also throttles the recursive calling so that it's only called once every 100 milliseconds, although that too can be overwritten with whatever value you like (in milliseconds) via the options parameter.
HTML:
<div id="messageBox"></div>
javaScript:
(function( $ ) {
var queue = false;
var counter = 0;
$.fn.messager = function(message, effect, speed, options) {
var _S = $.extend({
throttle: 100,
counter: 50
}, options);
var _this = $(this);
counter += 1;
function codeToRun() {
_this.fadeOut(speed, function() {
_this.text(message);
_this.fadeIn(speed, function() {
queue = false;
});
});
}
if (!queue) {
queue = true;
codeToRun();
counter = 0;
} else {
if (counter < _S.counter) {
setTimeout(function() {
_this.messager(message, effect, speed);
}, _S.throttle);
}
}
return this;
};
})( jQuery );
$('#messageBox').messager('One', 300);
$('#messageBox').messager('Two', 300);
$('#messageBox').messager('Three', 300);
For some reason, calling methods on $(this) directly gives me:
[Window, jquery: "1.11.0", constructor: function, selector: "", toArray: function, get: function…]
But storing $(this) in a variable and calling methods on that variable gives me the correct element:
[div#messageBox, selector: "#messageBox", context: document, jquery: "1.11.0", constructor: function, toArray: function…]
welcome all ,
i have a problem with my images slider , it runs successfuly until poll script excuted then it stops , tried to combine both scripts didn't work also tried to use noConflict but in stops both of them .
this is the slider
(function ($) {
$.fn.s3Slider = function (vars) {
var element = this;
var timeOut = (vars.timeOut != undefined) ? vars.timeOut : 4000;
var current = null;
var timeOutFn = null;
var faderStat = true;
var mOver = false;
var items = $("#sliderContent .sliderImage");
var itemsSpan = $("#sliderContent .sliderImage span");
items.each(function (i) {
$(items[i]).mouseover(function () {
mOver = true
});
$(items[i]).mouseout(function () {
mOver = false;
fadeElement(true)
})
});
var fadeElement = function (isMouseOut) {
var thisTimeOut = (isMouseOut) ? (timeOut / 2) : timeOut;
thisTimeOut = (faderStat) ? 10 : thisTimeOut;
if (items.length > 0) {
timeOutFn = setTimeout(makeSlider, thisTimeOut)
} else {
console.log("Poof..")
}
};
var makeSlider = function () {
current = (current != null) ? current : items[(items.length - 1)];
var currNo = jQuery.inArray(current, items) + 1;
currNo = (currNo == items.length) ? 0 : (currNo - 1);
var newMargin = $(element).width() * currNo;
if (faderStat == true) {
if (!mOver) {
$(items[currNo]).fadeIn((timeOut / 6), function () {
if ($(itemsSpan[currNo]).css("bottom") == 0) {
$(itemsSpan[currNo]).slideUp((timeOut / 6), function () {
faderStat = false;
current = items[currNo];
if (!mOver) {
fadeElement(false)
}
})
} else {
$(itemsSpan[currNo]).slideDown((timeOut / 6), function () {
faderStat = false;
current = items[currNo];
if (!mOver) {
fadeElement(false)
}
})
}
})
}
} else {
if (!mOver) {
if ($(itemsSpan[currNo]).css("bottom") == 0) {
$(itemsSpan[currNo]).slideDown((timeOut / 6), function () {
$(items[currNo]).fadeOut((timeOut / 6), function () {
faderStat = true;
current = items[(currNo + 1)];
if (!mOver) {
fadeElement(false)
}
})
})
} else {
$(itemsSpan[currNo]).slideUp((timeOut / 6), function () {
$(items[currNo]).fadeOut((timeOut / 6), function () {
faderStat = true;
current = items[(currNo + 1)];
if (!mOver) {
fadeElement(false)
}
})
})
}
}
}
};
makeSlider()
}
})(jQuery);
and this is the poll script
window.onload = function() {
$(".sidePollCon").load("ar_poll.html", function(r, s, xhr) {
if (s == "error") {
$(".sidePollCon").load("poll.html");
} else {
$(".vote_booroo").html("صوت الان");
$(".viewresults").html("شاهد النتيجة");
$("fieldset p").html("");
$(".results_booroo p").html("");
$(".result_booroo").attr("src", "../images/poll_color.jpg");
}
});
};
One potential problem could be the window.onload assignment. It is very prone to conflict.
Every time you do window.onload = the previous assignemnt will be overridden. See demo here:
The output shows that the first window.onload assignment never gets called, while the jQuery alternative does get called.
jQuery.noConflict does little in this regard. All it does is to prevent override the $ symbol so that another lib can use it.
So if you are also using the window.onload event to invoke the slider, then you have conflict. You can easily solve this problem by using the jquery format:
$(window).load(function() {
...
});
However usually you would tie the event to $(document).load(function(){...}); or in short form: $(function(){...}).
So for your poll that would be:
$(function(){
$(".sidePollCon").load("ar_poll.html", function(r, s, xhr) {
if (s == "error") {
$(".sidePollCon").load("poll.html");
} else {
$(".vote_booroo").html("صوت الان");
$(".viewresults").html("شاهد النتيجة");
$("fieldset p").html("");
$(".results_booroo p").html("");
$(".result_booroo").attr("src", "../images/poll_color.jpg");
}
});
});
Hope that helps.
resolving conflicts in jquery (possibly with another JS library .. like script.aculo.us) can be resolved using noconflict()
http://api.jquery.com/jQuery.noConflict/
$.noConflict();
but make sure that u have no error in your javascript code itself. use firebug and
console.log('') to test your script.
I have the following function :
var appendStructure = {
init : function(wrapper,structure,cls,callback) {
$(wrapper).appendTo(container).hide()
var object = $(container).find(cls);
$(structure.join('')).appendTo(object);
showObj(object,function() {
if(opts.centerObj == true) {
$(window).resize(function() {
var cssProps = getProps(object);
object.css(cssProps);
});
}
if(typeof callback == 'function') {
callback();
}
});
}
}
And the other functions that are called within it:
var getProps = function(obj) {
return {
'position' :'absolute',
'top' : (($(window).height() - $(obj).outerHeight()) / 2)+'px',
'left' : (($(window).width() - $(obj).outerWidth()) / 2)+'px'
}
}
var showObj = function(obj,callback) {
return setTimeout(function () {
if(opts.centerObj == true) {
var cssProps = getProps(obj);
obj.css(cssProps).fadeIn('slow');
}
else {
obj.fadeIn('slow');
}
if(typeof callback == 'function') {
callback();
}
}, 1500);
}
And I run the function like this:
if(appendStructure.init(wrapper.login,structure.login,'.content-login')){
console.log('Object Appended');
}
else {
console.log('Error');
}
My question is, why is the console outputting Error, because the function actually works and everything that is suppose to happen, happens ?
appendStructure.init does not return any value, hence the return value will be undefined. undefined evaluates to false, so the else branch of your if...else statement is executed.