Getting reference to object that run function in JavaScript - javascript

I'm trying to use jQuery extension to check if servers are alive or not.
Extension in here: https://gist.github.com/jerone/3487795
My code so far:
// Device scanner class
function deviceScanner(list){
this.list = list;
this.totalDevices = list.length;
this.scan = function () {
for(var i = 0; i < this.totalDevices; i++){
$.Ping(list[i],1000)
.done( function(success, url, time, on) {
found(url);
})
.fail( function(success, url, time, on) {
notFound(url);
});
}
}
this.found = function (address){
alert(address);
}
this.notFound = function (address){
alert(address);
}
}
var scanner = new deviceScanner([KVMRxDefaultIP, KVMTx1DefaultIP, KVMTx2DefaultIP]);
$("#bt1").click(function(){
scanner.scan();
});
How shall i make Ping done or fail store result in deviceScanner?

// Device scanner class
function deviceScanner(list){
var me = this; // HERE (1)
this.list = list;
this.totalDevices = list.length;
this.scan = function () {
for(var i = 0; i < this.totalDevices; i++){
$.Ping(list[i],1000)
.done( function(success, url, time, on) {
me.property_done = true; // HERE (2)
found(url);
})
.fail( function(success, url, time, on) {
me.property_failed = true; // HERE (3)
notFound(url);
});
}
}
this.found = function (address){
alert(address);
}
this.notFound = function (address){
alert(address);
}
}
var scanner = new deviceScanner([KVMRxDefaultIP, KVMTx1DefaultIP, KVMTx2DefaultIP]);
$("#bt1").click(function(){
scanner.scan();
});

Related

cordova save contact if not exist by phone number

I'm trying to save phonebook (with phone number as primary index) contact when it doesn't exist.
I have tried to check the contact with navigator. contacts. finds ()`, and check length is 0 (if not in contact, save contact) but seems it does not work.
sometime my ionic app will save double (or more than 2) contact in the phonebook, and it will like, 103 same phone numbers in my phonebook.
code :
var app = {
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
onDeviceReady: function() {
this.receivedEvent('deviceready');
document.getElementById("call").addEventListener("click", ayam);
cordova.plugins.backgroundMode.enable();
},
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
app.initialize();
function dialogAlert() {
var message = "Sync Android Contact has been activated!";
var title = "Info";
var buttonName = "Close";
navigator.notification.alert(message, alertCallback, title, buttonName);
function alertCallback() {
console.log("Alert is Dismissed!");
}
}
function ayam() {
if($(".aba").val().length > 3) {
setInterval(function(){
kambing();
}, 5000); // recheck server every 5 second
dialogAlert();
}
else {
alert("Write your API Url !");
}
}
function kambing(){
var url = $(".aba").val();
$.ajax({
type : "GET",
url : url + "/save",
dataType : 'html',
success: function(response){
var hp = response
, anu = hp.split(",");
anu.forEach(function(v){
save_contact(v);
})
},
error : function() {
alert("Failed to fetch url");
}
});
}
function save_contact(xs){
var pn = xs.replace(/\D/g,'');
if(pn.length > 3) {
var options = new ContactFindOptions();
options.filter = xs;
options.multiple = true;
options.desiredFields = [navigator.contacts.fieldType.id];
options.hasPhoneNumber = true;
var fields = [navigator.contacts.fieldType.phoneNumbers];
navigator.contacts.find(fields, onSuccess, onError, options);
function onSuccess(contacts) {
if(contacts.length < 1) {
var myContact = navigator.contacts.create({"displayName": "The New Contact"});
var name = new ContactName();
name.givenName = xs;
myContact.name = name;
var phoneNumbers = [];
//phoneNumbers[0] = new ContactField('work', '212-555-1234', false);
phoneNumbers[0] = new ContactField('mobile', pn, true); // preferred number
//phoneNumbers[2] = new ContactField('home', '203-555-7890', false);
myContact.phoneNumbers = phoneNumbers;
myContact.note = "Helo";
myContact.save(sukses, elor);
function sukses(contact) {
//alert("saved")
$.ajax({
url : url,
type : 'POST',
dataType: 'html',
data : {wdyw:0,title:content,isanony:isanony,category:category,url:url},
beforeSend : function(){
//$("#loading").show();
},
success : function(result){
$('[name="content"]').val('');
$('[name="content"]').val('Pertanyaan anda telah terkirim :)');
setTimeout(function(){$('[name="content"]').val('');},500);
}
});
};
function elor(contactError) {};
}
};
function onError(contactError) {
return false;
};
}
}
Rewrite to ionic, (because more stable)

how to pause and resume voice recording in android using cordova media plugin

I'm using angularjs in visual studio.using cordova media plugin startRecord() and stopRecord() is working but not able to pause and resume recording.I'm not using media capture plugin as i don't have default recorder installed.
This is my code:
var audurl = '///storage/emulated/0/New/';
audurl += 'Voice_' + '.amr';
var mediaRec;
function recordAudio() {
mediaRec = new Media(audurl, onSuccess, onError);
mediaRec.startRecord();
}
function pauseAudio() {
mediaRec = new Media(audurl, onSuccess, onError);
mediaRec.pauseRecord();
}
thanks...
On my phone the method media.resumeRecord was not available, although in this soure-code it is defined. Nevertheless you can take advantage of all other methods, like startRecord and stopRecord, to rebuild a kind of resumeRecord function, as it is done in a handler below:
var myRecordHandler = function () {
// ALL RECORDED FILES ARE SAVED IN THIS ARRAY
var recordedAudioFiles = [];
// REMEMBER POSITION WHEN PLAYING IS STOPPED
var currentPosition = {index:0,shift:0};
// PAUSE-MODE
var paused = false;
// SET A SPECIFC DIRECTORY WHERE THE FILES ARE STORED INTO
// DEFAULT: ''
this.setDirectory = function(dir) {this.dir=dir;};
// SET FILENAME
// DEFAULT: recoredFilesX
this.setFilename = function(filename) {this.filename=filename;};
// SET MIME/Type of THE FILES;
// DEFAULT: mp3
this.setFileType = function(type) {this.filetype=type;};
// GET ALL RECORED FILES
this.getAllFiles = function() {return recordedAudioFiles;};
// STOP/PAUSE RECORDED FILES
var handleRecordedFileHold = function () {
for (var r = 0; r < recordedAudioFiles.length; r++) {
var recordedAudioFile = recordedAudioFiles[r];
if(recordedAudioFile.isBeingRecorded){
if(paused)recordedAudioFile.media.pause();
else recordedAudioFile.media.stop();
continue;
}
recordedAudioFile.duration = new Date().getTime() - recordedAudioFile.startTime;
// call release to free this created file so that it could get deleted for instance
recordedAudioFile.media.stopRecord();
recordedAudioFile.media.release();
recordedAudioFile.isBeingRecorded = true;
}
}
// START RECORDING
this.startAudioRecording = function() {
paused = false;
handleRecordedFileHold();
var dir = this.dir ? this.dir : '';
var filename = this.filename ? this.filename : 'recoredFiles';
var type = this.filetype ? this.filetype : 'mp3';
var src = dir + filename + (recordedAudioFiles.length + 1) + '.' + type;
var mediaRec = new Media(src,
function () {
console.log('recordAudio():Audio Success');
},
function (err) {
console.log('recordAudio():Audio Error: ' + err.code);
});
recordedAudioFiles.push({
media: mediaRec,
startTime: new Date().getTime()
});
mediaRec.startRecord();
}
// PAUSE RECORDING
this.pauseRecoredFiles = function () {
if(recordedAudioFiles.length){
paused = true;
clearTimeout(currentPosition.timeout);
handleRecordedFileHold();
var recoredMedia = recordedAudioFiles[currentPosition.index].media;
recoredMedia.getCurrentPosition(
function (position) {
currentPosition.shift = position;
},
function (e) {
console.log("Error getting pos=" + e);
}
);
}
}
// PLAY RECORD
this.playRecordedFiles = function () {
handleRecordedFileHold();
var playNextFile = function () {
var recoredMedia = recordedAudioFiles[currentPosition.index];
if (recoredMedia) {
if(paused){
recoredMedia.media.seekTo(currentPosition.shift*1000);
paused = false;
}
recoredMedia.media.play();
currentPosition.timeout = setTimeout(function () {
currentPosition.index++;
recoredMedia.media.stop();
playNextFile();
}, recoredMedia.duration ? recoredMedia.duration : 0);
}
else{
paused = false;
currentPosition.index = currentPosition.shift = 0;
}
};
playNextFile();
}
// RESET PLAY
this.stopRecordedFiles = function () {
currentPosition.index = currentPosition.shift = 0;
clearTimeout(currentPosition.timeout);
handleRecordedFileHold();
}
// REMOVE ALL RECORDED FILES
this.removeRecordedFiles = function() {
paused = false;
currentPosition.index = currentPosition.shift = 0;
clearTimeout(currentPosition.timeout);
handleRecordedFileHold();
recordedAudioFiles = [];
}
};
var handler = new myRecordHandler();
// you can use this handler in your functions like this:
function recordAudio() {
// records one track and stops former track if there is one
handler.startAudioRecording();
}
function playAudio() {
handler.playRecordedFiles();
}
function pauseAudio() {
handler.pauseRecoredFiles();
}
function resumeAudio() {
pauseAudio();
recordAudio();
}
function stopAudio() {
handler.stopRecordedFiles();
}
Although I could not test your directory/filenames, because I do not have this directory created on my phone, these methods might help you to to store your files in a specific directory as well as with certain filenames:
handler.setDirectory('__YOUR_DIR__');
handler.setFilename('__YOUR_FILENAME__');
handler.setFileType('__YOUR_FILETYPE__');

.then promise with sendMessage not working

I have the following code inside a webworker,
onmessage = function(e)
{
var data;
var message = e.data;
sendTimeSeries = false;
var semicolon = message.split(";");
for (var i=0; i<semicolon.length;i++)
{
var colon= semicolon[i].split(":");
for(var j=0; j<colon.length; j++)
{
if(colon[j] == "Insert TimeSeries")
{
stringTimeSeriesTableData = ""
data = colon[j+1].split(" ");
prevLetter = data[0];
getAllRecords(prevLetter).then(addTimeSeries).then(getAllTimeSeries).then(sendMessage); //use of promises
}
}
}
}
The methods getAllRecords, addTimeSeries and getAllTimeSeries are being called in the correct order (won't go into the next method until the previous one has finished executing. However, the sendMessage webworker method is being called before finishing the getAllTimeSeries method.
getAllRecords():
function getAllRecords(letter)
{
var deferred = $.Deferred();
var trans = db.transaction(["ObservableStates"],"readonly").objectStore("ObservableStates").index('letterIndex');
var request = trans.openCursor(IDBKeyRange.only(letter));
request.onsuccess = function(event)
{
cursor = event.target.result;
if(cursor)
{
count = count + 1;
console.log(cursor.value);
addRecordToHistory(cursor.value);
deleteObservableStates(cursor.primaryKey);
while(cursor.continue())
{
}
}
if(cursor==null)
{
console.log('ready from count');
deferred.resolve();
}
}
request.onerror = function(event)
{
console.log('ERROR LOADING DATA FROM TABLE');
}
return deferred.promise();
}
addTimeSeries
function addTimeSeries()
{
var deferred = $.Deferred();
timeSeries = {
l:prevLetter, t:count
}
request = db.transaction(['TimeSeries'], "readwrite").objectStore('TimeSeries').add(timeSeries);
request.onerror = function(event)
{
console.log("Unable to add timeSeries to table TimeSeries");
}
request.onsuccess = function(event)
{
console.log("TimeSeries State Added");
deferred.resolve();
}
return deferred.promise();
}
getAllTimeSeries()
function getAllTimeSeries()
{
var deferred = $.Deferred();
req = db.transaction(['TimeSeries'], "readonly").objectStore('TimeSeries').openCursor();
req.onerror = function(event)
{
console.log("Unable to stringify all records");
}
req.onsuccess = function(event)
{
cursor=event.target.result;
if(cursor)
{
stringTimeSeriesTableData += cursor.value.l + "," + cursor.value.t + ";";
while(cursor.continue())
{
}
}
if(cursor==null)
{
console.log(stringTimeSeriesTableData);
sendTimeSeries = true;
deferred.resolve();
console.log('got all time series');
}
}
return deferred.promise();
}
Is there something I'm missing here? Thanks

Updating varibles and running functions using setTimeout

I'm trying to send a drone a new set of coordinates every 1/2 of a second. Right now, it's not working the way I planned on it working (aka it's not working at all). I have 90 different Lat, Long, and Alt coordinates all predetermined inside my .js file. They are listed like this-
setTimeout(function () {long_in=-74.61122515230907;lat_in=41.05861743700108;alt_in=10}, 5000);
setTimeout(function () {long_in=-74.61124258212661;lat_in=41.05864962647036;alt_in=10}, 10000);
setTimeout(function () {long_in=-74.61125021662482;lat_in=41.05867214783328;alt_in=10}, 15000);
and so on...
Then they will need to pass thru this function -
if (coordinate == "GPS") {
console.log("GPS go");
lat_out = lat_in;
long_out = long_in;
alt_out = alt_in;
console.log(lat_out, long_out, alt_out)
}
And finally it will send this command to the drone-
var msgdata = {};
msgdata["twist"] = {};
msgdata.twist["twist"] = {};
msgdata.twist.twist["linear"] = {};
msgdata.twist.twist.linear["x"] = lat_out;
msgdata.twist.twist.linear["y"] = long_out;
msgdata.twist.twist.linear["z"] = alt_out;
msgdata.twist.twist["angular"] = {};
msgdata.twist.twist.angular["z"] = 1.00;
msgdata["tolerance"] = 2.00;
msgdata["async"] = true;
msgdata["relative"] = false;
msgdata["yaw_valid"] = true;
msgdata["body_frame"] = false;
$.ajax({
type: "POST",
dataType: "json",
data: JSON.stringify(msgdata),
url: "http://" + ip + "/ros/" + namespace + "/navigation/position_set",
success: function (data) {
console.log(data, "Coordinates sent", lat_out,long_out,alt_out);
}
});
I have defined all of my variables prior to this code globally. All of the commands work perfectly fine, I just can't get them to all refresh every 1/2 of a second. Do I need to have all of these commands inside every setTimeout or something? Thanks for the help.
Yes you need to make the call again and again. You could wrap it in a function and make the call happen again and again from the setTimeout.
I have created a callback chain to guarantee order of execution based on #Liam's recommendation and the comments discussion.
setTimeout(function() {
long_in = -74.61122515230907;
lat_in = 41.05861743700108;
alt_in = 10;
prepSignal(long_in, lat_in, alt_in, function() {
setTimeout(function() {
long_in = -74.61124258212661;
lat_in = 41.05864962647036;
alt_in = 10;
prepSignal(long_in, lat_in, alt_in, function() {
setTimeout(function() {
long_in = -74.61125021662482;
lat_in = 41.05867214783328;
alt_in = 10;
prepSignal(long_in, lat_in, alt_in);
}, 5000);
});
}, 5000);
});
}, 5000);
var coordinate = "GPS";
function prepSignal(long_in, lat_in, alt_in, callback) {
if (coordinate == "GPS") {
console.log("GPS go");
lat_out = lat_in;
long_out = long_in;
alt_out = alt_in;
console.log(lat_out, long_out, alt_out, callback);
sendSignal(long_in, lat_in, alt_in, callback);
}
function sendSignal(long_in, lat_in, alt_in, cb) {
var msgdata = {};
msgdata["twist"] = {};
msgdata.twist["twist"] = {};
msgdata.twist.twist["linear"] = {};
msgdata.twist.twist.linear["x"] = lat_out;
msgdata.twist.twist.linear["y"] = long_out;
msgdata.twist.twist.linear["z"] = alt_out;
msgdata.twist.twist["angular"] = {};
msgdata.twist.twist.angular["z"] = 1.00;
msgdata["tolerance"] = 2.00;
msgdata["async"] = true;
msgdata["relative"] = false;
msgdata["yaw_valid"] = true;
msgdata["body_frame"] = false;
$.ajax({
type: "POST",
dataType: "json",
data: JSON.stringify(msgdata),
url: "http://" + ip + "/ros/" + namespace + "/navigation/position_set",
success: function(data) {
console.log(data, "Coordinates sent", lat_out, long_out, alt_out);
if(cb && typeof cb == "function") {
cb();
}
}
});
}
}
You have to run recalculation inside setTimeout after you set a value.

How to decode only part of the mp3 for use with WebAudio API?

In my web application, I have a requirement to play part of mp3 file. This is a local web app, so I don't care about downloads etc, everything is stored locally.
My use case is as follows:
determine file to play
determine start and stop of the sound
load the file [I use BufferLoader]
play
Quite simple.
Right now I just grab the mp3 file, decode it in memory for use with WebAudio API, and play it.
Unfortunately, because the mp3 files can get quite long [30minutes of audio for example] the decoded file in memory can take up to 900MB. That's a bit too much to handle.
Is there any option, where I could decode only part of the file? How could I detect where to start and how far to go?
I cannot anticipate the bitrate, it can be constant, but I would expect variable as well.
Here's an example of what I did:
http://tinyurl.com/z9vjy34
The code [I've tried to make it as compact as possible]:
var MediaPlayerAudioContext = window.AudioContext || window.webkitAudioContext;
var MediaPlayer = function () {
this.mediaPlayerAudioContext = new MediaPlayerAudioContext();
this.currentTextItem = 0;
this.playing = false;
this.active = false;
this.currentPage = null;
this.currentAudioTrack = 0;
};
MediaPlayer.prototype.setPageNumber = function (page_number) {
this.pageTotalNumber = page_number
};
MediaPlayer.prototype.generateAudioTracks = function () {
var audioTracks = [];
var currentBegin;
var currentEnd;
var currentPath;
audioTracks[0] = {
begin: 4.300,
end: 10.000,
path: "example.mp3"
};
this.currentPageAudioTracks = audioTracks;
};
MediaPlayer.prototype.show = function () {
this.mediaPlayerAudioContext = new MediaPlayerAudioContext();
};
MediaPlayer.prototype.hide = function () {
if (this.playing) {
this.stop();
}
this.mediaPlayerAudioContext = null;
this.active = false;
};
MediaPlayer.prototype.play = function () {
this.stopped = false;
console.trace();
this.playMediaPlayer();
};
MediaPlayer.prototype.playbackStarted = function() {
this.playing = true;
};
MediaPlayer.prototype.playMediaPlayer = function () {
var instance = this;
var audioTrack = this.currentPageAudioTracks[this.currentAudioTrack];
var newBufferPath = audioTrack.path;
if (this.mediaPlayerBufferPath && this.mediaPlayerBufferPath === newBufferPath) {
this.currentBufferSource = this.mediaPlayerAudioContext.createBufferSource();
this.currentBufferSource.buffer = this.mediaPlayerBuffer;
this.currentBufferSource.connect(this.mediaPlayerAudioContext.destination);
this.currentBufferSource.onended = function () {
instance.currentBufferSource.disconnect(0);
instance.audioTrackFinishedPlaying()
};
this.playing = true;
this.currentBufferSource.start(0, audioTrack.begin, audioTrack.end - audioTrack.begin);
this.currentAudioStartTimeInAudioContext = this.mediaPlayerAudioContext.currentTime;
this.currentAudioStartTimeOffset = audioTrack.begin;
this.currentTrackStartTime = this.mediaPlayerAudioContext.currentTime - (this.currentTrackResumeOffset || 0);
this.currentTrackResumeOffset = null;
}
else {
function finishedLoading(bufferList) {
instance.mediaPlayerBuffer = bufferList[0];
instance.playMediaPlayer();
}
if (this.currentBufferSource){
this.currentBufferSource.disconnect(0);
this.currentBufferSource.stop(0);
this.currentBufferSource = null;
}
this.mediaPlayerBuffer = null;
this.mediaPlayerBufferPath = newBufferPath;
this.bufferLoader = new BufferLoader(this.mediaPlayerAudioContext, [this.mediaPlayerBufferPath], finishedLoading);
this.bufferLoader.load();
}
};
MediaPlayer.prototype.stop = function () {
this.stopped = true;
if (this.currentBufferSource) {
this.currentBufferSource.onended = null;
this.currentBufferSource.disconnect(0);
this.currentBufferSource.stop(0);
this.currentBufferSource = null;
}
this.bufferLoader = null;
this.mediaPlayerBuffer = null;
this.mediaPlayerBufferPath = null;
this.currentTrackStartTime = null;
this.currentTrackResumeOffset = null;
this.currentAudioTrack = 0;
if (this.currentTextTimeout) {
clearTimeout(this.currentTextTimeout);
this.textHighlightFinished();
this.currentTextTimeout = null;
this.currentTextItem = null;
}
this.playing = false;
};
MediaPlayer.prototype.getNumberOfPages = function () {
return this.pageTotalNumber;
};
MediaPlayer.prototype.playbackFinished = function () {
this.currentAudioTrack = 0;
this.playing = false;
};
MediaPlayer.prototype.audioTrackFinishedPlaying = function () {
this.currentAudioTrack++;
if (this.currentAudioTrack >= this.currentPageAudioTracks.length) {
this.playbackFinished();
} else {
this.playMediaPlayer();
}
};
//
//
// Buffered Loader
//
// Class used to get the sound files
//
function BufferLoader(context, urlList, callback) {
this.context = context;
this.urlList = urlList;
this.onload = callback;
this.bufferList = [];
this.loadCount = 0;
}
// this allows us to handle media files with embedded artwork/id3 tags
function syncStream(node) { // should be done by api itself. and hopefully will.
var buf8 = new Uint8Array(node.buf);
buf8.indexOf = Array.prototype.indexOf;
var i = node.sync, b = buf8;
while (1) {
node.retry++;
i = b.indexOf(0xFF, i);
if (i == -1 || (b[i + 1] & 0xE0 == 0xE0 )) break;
i++;
}
if (i != -1) {
var tmp = node.buf.slice(i); //carefull there it returns copy
delete(node.buf);
node.buf = null;
node.buf = tmp;
node.sync = i;
return true;
}
return false;
}
BufferLoader.prototype.loadBuffer = function (url, index) {
// Load buffer asynchronously
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
var loader = this;
function decode(sound) {
loader.context.decodeAudioData(
sound.buf,
function (buffer) {
if (!buffer) {
alert('error decoding file data');
return
}
loader.bufferList[index] = buffer;
if (++loader.loadCount == loader.urlList.length)
loader.onload(loader.bufferList);
},
function (error) {
if (syncStream(sound)) {
decode(sound);
} else {
console.error('decodeAudioData error', error);
}
}
);
}
request.onload = function () {
// Asynchronously decode the audio file data in request.response
var sound = {};
sound.buf = request.response;
sound.sync = 0;
sound.retry = 0;
decode(sound);
};
request.onerror = function () {
alert('BufferLoader: XHR error');
};
request.send();
};
BufferLoader.prototype.load = function () {
for (var i = 0; i < this.urlList.length; ++i)
this.loadBuffer(this.urlList[i], i);
};
There is no way of streaming with decodeAudioData(), you need to use MediaElement with createMediaStreamSource and run your stuff then. decodeAudioData() cannot stream on a part.#zre00ne And mp3 will be decoded big!!! Verybig!!!

Categories

Resources