I'm using Phonegap to create an Android application (Voice Recorder), but I had these 2 errors in my code:
ReferenceError: Can't find variable: Media.
TypeError: Result of expression 'mediaRec' undefined is not an object.
The first error happens when the application runs. The second error happens when I call the recordAudio(); method.
Tell me what's the problem please if you know.
var mediaRec;
var src;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
}
function init() {
document.getElementById('status').innerHTML = "Recording Status";
src = "myrecording.mp3";
mediaRec = new Media(src, onSuccess, onError);
}
function recordAudio() {
// Record audio
mediaRec.startRecord();
// Stop recording after 10 sec
var recTime = 0;
var recInterval = setInterval(function() {
recTime = recTime + 1;
setAudioPosition(recTime + " sec");
if (recTime >= 10) {
clearInterval(recInterval);
}
}, 1000);
}
// Stop audio
function stopRecording() {
if (mediaRec) {
mediaRec.stopRecord();
}
clearInterval(mediaTimer);
mediaTimer = null;
}
// onSuccess Callback
function onSuccess() {
console.log("recordAudio():Audio Success");
}
// onError Callback
function onError(error) {
alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}
// Set audio position
function setAudioPosition(position) {
document.getElementById('rec_position').innerHTML = position;
}
Thanks.
I think scr = "/android_asset/www/myrecording.mp3" because directory phonegap in asset/www/...
If directory not found javascript in phonegap show alert like that ReferenceError: Can't find variable: Media.
Be sure to add the 'cordova-plugin-media' plugin which defines a global Media constructor. See Cordova media documentation
cordova plugin add cordova-plugin-media --save
The other reason this might happen is be sure to wait until device is ready Cordova event before new Media constructor is called.
Related
I have a file dmreboot_service.js in my /js folder. When I run this file using node /js/dmreboot_service.js it successfully invokes a direct method in Azure.
I need to be able to execute this function or file on a button click from my web app.
I tried loading the script into the head of my html using :
<script src="js/dmreboot_service.js"></script>
I put an alert in the external file.
If I put this alert at the top of the file it works, but at
the bottom it fails, so the contents of the file are not loading.
The content of dmreboot_service.js is :
'use strict';
var Registry = require('azure-iothub').Registry;
var Client = require('azure-iothub').Client;
var connectionString ="HostName=XxxxxxxX.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=XxxxxxxxxxxxxxxxxxxxxxxxxxxxxxX=";
var registry = Registry.fromConnectionString(connectionString);
var client = Client.fromConnectionString(connectionString);
var deviceToReboot = 'Runner';
var startRebootDevice = function (twin) {
var methodName = "reboot";
var methodParams = {
methodName: methodName,
payload: null,
timeoutInSeconds: 30
};
client.invokeDeviceMethod(deviceToReboot, methodParams, function(err, result) {
if (err) {
console.error("Direct method error: "+err.message);
} else {
console.log("Successfully invoked the device to reboot.");
}
});
};
var queryTwinLastReboot = function() {
registry.getTwin(deviceToReboot, function(err, twin){
if (twin.properties.reported.iothubDM != null)
{
if (err) {
console.error('Could not query twins: ' + err.varructor.name + ': ' + err.message);
} else {
var lastRebootTime = twin.properties.reported.iothubDM.reboot.lastReboot;
console.log('Last reboot time: ' + JSON.stringify(lastRebootTime, null, 2));
}
} else
console.log('Waiting for device to report last reboot time.');
});
};
startRebootDevice();
setInterval(queryTwinLastReboot, 2000);
alert('dmreboot included!');
I have also tried creating a function in the head of my html that includes the entire contents of dmreboot_service.js, but although the function is called successfully the code does not execute.
This is the last part of a project that I need to get working. I'm fairly new to this, and this is driving me nuts!! Any advice much appreciated.
I usually handle click in HTML with javascript like so;
const doSomething = document.querySelector('.whateverclassnameyouchoose').addEventListener('click',onClick);
function onClick(e){
what ever you want the function to do
}
Hope it helps :)
I searched for a while but couldn't find a working solution for my particular problem.
I have the "default" WebSocket implementation in my JavaScript file. It works but it does not work everytime. Sometimes (can be the first time but could also be the 101st time) the event don't fire. Shouldn't at least the onclose-event fire with wasClean == false?
Maybe someone can help me out with this.
Edit: Forgot something. Only happens if I provide a wrong IP-Adress for:
ws = new WebSocket("ws://" + ip + ":9999/");
So server-side code is not necessary to answer this question.
$(document).ready(function () {
ws = new WebSocket("ws://" + ip + ":9999/");
ws.onopen = function(evt) {
console.log("CONNECTED");
doSend("getInfo");
};
ws.onclose = function(evt) {
if (!evt.wasClean) {
showError();
return;
}
console.log("DISCONNECTED");
};
ws.onmessage = function(evt) {
newIP = evt.data;
};
});
Solved it myself.
Problem was that the no-route-to-host error wasn't firing fast enough if there is no device behind the given IP-Adress. So I implemented a timeout which checks if the readyState of the socket is zero after 100 ms (Application runs in a Local Area Network so the time should be large enough)
function checkServer(ip, port) {
var ws = new WebSocket("ws://" + ip + ":" + port);
setTimeout(function() {
if (ws.readyState == 0) {
showError();
}
else {
ws.close();
ConnectToServer();
}
}, 100);
}
I fork workers in my Node.js application via the Cluster module and pass a custom ID to the environment of all my workers. That works well for far.
However, I do not know how I can access this id in my master when an 'online' or 'exit' event is emitted.
The documentation is not very helpful. Could you please point me the right way?
var cluster = require('cluster');
if (cluster.isMaster) {
//MASTER
function fork() {
var worker_env = {worker_id:'my_custom_id'};
cluster.fork(worker_env);
}
cluster.on('online', function(worker) {
console.log(worker.process.env.worker_id); // undefined
//
// How can I access my custom worker id here?
//
});
cluster.on('exit', function(worker, code, signal) {
//
// And here...?
//
fork();
});
} else {
// WORKER
console.log(process.env.worker_id); // my_custom_id
}
theres no way, the worker process env is not exposed to the master.
One aproach can be a map of our cluster (a object containig the needed info).
Something like these:
var cluster = require('cluster');
if (true === cluster.isMaster) {
//CODE EXECUTED BY MASTER
var cluster_map = {}; // Here we store the workers info in a object
var restart_Limit = 10; // max global worker restart (10)
function fork_worker(myWorkerId) {
// these makes worker_id available in the worker
var worker = cluster.fork({
worker_id: myWorkerId
});
// max restarts limit (global)
if (worker.id >= restart_Limit) {
console.log('Restart limit reached, bye!');
process.kill();
}
// here we add the key "myWorkerId" to the cluster map
cluster_map[worker.id] = myWorkerId;
// WORKER AUTO-KILL
setTimeout(function() {
console.log('stoping...' + myWorkerId);
worker.kill();
}, 3000);
}
cluster.on('online', function(worker) {
var online_proc = cluster_map[worker.id];
console.log('worker online: ' + online_proc + '\n Restarts: ' + worker.id);
});
cluster.on('exit', function(worker, code, signal) {
var exited_proc = cluster_map[worker.id];
// delete the process from the cluster map
delete cluster_map[worker.id];
console.log("worker offline: " + exited_proc);
// WORKER AUTO-RESTART
setTimeout(function() {
console.log('Restarting... ' + exited_proc);
fork_worker(exited_proc);
}, 3000);
});
// start the magic ( 3 workers )
(function() {
fork_worker('id_1');
fork_worker('id_2');
fork_worker('id_3');
})();
} else {
//CODE EXECUTED BY EACH WORKER (process env is present here).
console.log('hi from the worker, process.env: ' + process.env.worker_id);
// all the hard work for the workers here.
}
I am following the example presented here
to create a server that would run on multiple cores.I get the following error:
created worker: undefined
created worker: undefined
created worker: undefined
created worker: undefined
workers[m.process].lastCb=new Date().getTime();
^
TypeError: Cannot set property 'lastCb' of undefined
at Worker.<anonymous> (/home/anr/Desktop/node js/clustering2.js:56:29)
at Worker.EventEmitter.emit (events.js:98:17)
at ChildProcess.EventEmitter.emit (events.js:98:17)
at handleMessage (child_process.js:318:10)
at Pipe.channel.onread (child_process.js:345:11)
This is my code:
var cluster=require('cluster');
var os=require('os');
var http=require('http');
var numCores=os.cpus().length;
var rsswarn=(50*1024*1024),
heapWarn=(50*1024*1024);
var workers={};
if(cluster.isMaster)
{
for(var i=0;i<numCores;i+=1)
{
createWorker();
}
setInterval(function killWorkers(){
var time=new Date().getTime();
for(pid in workers)
{
if(workers.hasOwnProperty(pid) && workers[pid].lastCb+5000<time)
{
console.log('Long running process '+pid+ ' killed');
workers[pid].worker.kill();
delete workers[pid];
createWorker();
}
}
},1000);
}
else
{
http.Server(function makeServer(req,res){
if (Math.floor(Math.random() * 200) === 4) {
console.log('Stopped ' + process.pid + ' from ever finishing');
while(true) { continue; }
}
res.writeHead(200);
res.end('hello world from ' + process.pid + '\n');
}).listen(8000);
//Report stats once a second
setInterval(function report(){
process.send({cmd: "reportMem", memory: process.memoryUsage(), process: process.pid});
}, 1000);
}
function createWorker()
{
var worker=cluster.fork();
console.log('created worker: '+worker.pid);
workers[worker.pid]={worker:worker,lastCb:(new Date().getTime()-1000)};
worker.on('message',function(m){
if(m.cmd==='reportMem')
{
workers[m.process].lastCb=new Date().getTime();
if(m.memory.rss>rssWarn)
{
console.log('worker thread '+m.process+' taking too much memory');
}
}
});
}
You will find the pid in worker.process.pid. Either the example has a typo, or this has changed for newer versions of node.js.
// This works:
console.log('created worker: ' + worker.process.pid);
Reference: worker.process and ChildProcess.pid
After changing all worker.pid to worker.process.pid you will also notice there is a typo with the variable rsswarn which is later called as rssWarn
After fixing these two things, your code should work.
Have fun!
I'm new to signalr. I've started an MVC 4.0 application, out of the box, and wired up my signalr JavaScript on the Index View. When I click either the Register or Login buttons, signalr throws a JavaScript error.
Unhandled exception at line 11, column 10700 in http://localhost:49172/Scripts/jquery.signalR- 0.5.1.min.js
0x800a138f - Microsoft JScript runtime error: Unable to set value of the property 'src': object is null or undefined
Any suggestions appreciated.
EDIT:
This is the extent of my code:
$(function () {
var blasht = $.connection.blashtHub;
blasht.addMessage = function (message) {
$('#messages').append('<li>' + message + '');
};
$("#blashtIt").click(function () {
var control = $('#blashtText');
var control2 = $('#hiddenUserId');
// Call the chat method on the server
blasht.send(control2.val(), control.val());
control.val('');
});
blasht.updateTopTen = function (message) {
//add code to update the top user's list
};
// Start the connection
$.connection.hub.start();
});
As suggested I dropped the min and here is where it is crashing, on the frame.sc = src; line.
reconnect: function (connection) {
var that = this;
window.setTimeout(function () {
var frame = connection.frame,
src = transportLogic.getUrl(connection, that.name, true) + "&frameId=" + connection.frameId;
connection.log("Upating iframe src to '" + src + "'.");
frame.src = src;
}, connection.reconnectDelay);
},
SignalR, not me, is invoking this reconnect function. Obviously, that is how it maintains a connection with the server.
The is a bug in the current version of SignalR for the "Forever-Frame" implementation, which is the one that IE9 uses:
https://github.com/SignalR/SignalR/issues/446
A workaround is to force SignalR not to use Forever-Frame transport (https://github.com/SignalR/SignalR/wiki/SignalR-JS-Client).
So change
$.connection.hub.start();
to
$.connection.hub.start({ transport: ['webSockets', 'serverSentEvents', 'longPolling'] });
From the error message, and without your having shown any code, I'd have to guess that you have code that looks like this:
foo.src = someValue;
...where foo is null or undefined. Which begs the question of why is foo null or undefined, but without more context, it's impossible to say. Stepping through with the IE8+ "F12 Developer Tools" may help you pinpoint it.
(Update after code was posted)
I'm guessing that the line causing the error is frame.src = src;. Reformatting that code with consistent indentation:
reconnect: function (connection) {
var that = this;
window.setTimeout(function () {
var frame = connection.frame,
src = transportLogic.getUrl(connection, that.name, true) + "&frameId=" + connection.frameId;
connection.log("Upating iframe src to '" + src + "'.");
frame.src = src; // <=== Presumably this is the line failing
}, connection.reconnectDelay);
},
It would appear that as of the time the delayed function is called, connection.frame is null or undefined. So you'll need to find out why that is. The first thing I'd do is check whether connection.frame is null or undefined when reconnect is called, or if it's only later when the delayed function runs (e.g., has something cleared it in the meantime, and if so, why).