I'm working on mobile device (iOS). I develop a hybrid application using HTML/CSS/Javascript.
I have this code founded on Apache Cordova API :
<!DOCTYPE html>
<html>
<head>
<title>Capture Audio</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.5.0.js"></script>
<script type="text/javascript" charset="utf-8" src="json2.js"></script>
<script type="text/javascript" charset="utf-8">
// Called when capture operation is finished
//
function captureSuccess(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
}
// Called if something bad happens.
//
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
// A button will call this function
//
function captureAudio() {
// Launch device audio recording application,
// allowing user to capture up to 2 audio clips
navigator.device.capture.captureAudio(captureSuccess, captureError, {limit: 2});
}
// Upload files to server
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
ft.upload(path,
"http://my.domain.com/upload.php",
function(result) {
console.log('Upload success: ' + result.responseCode);
console.log(result.bytesSent + ' bytes sent');
},
function(error) {
console.log('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}
</script>
</head>
<body>
<button onclick="captureAudio();">Capture Audio</button> <br>
</body>
</html>
I can capture my voice with it and in theory upload it to
http://my.domain.com/upload.php
But I wonder how to adapt this code to upload file on my Dropbox . Is it possible to upload file to Dropbox as easy as that ?
As #sinaneker mentioned, you can do this server-side with PHP (or other languages).
But you can also do this directly from JavaScript using Dropbox's JavaScript library: https://github.com/dropbox/dropbox-js
Related
I have a problem please help me,
I have a sound recording page without interface, but I can not know which audio track was recorded,
Is there a way to know the track of a recorded sound or not?
I just want the audio track to play the audio track
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
recordAudio();
}
// Record audio
//
function recordAudio() {
var srcd = "myrecording" + Math.random() + ".wav";
var mediaRec = new Media(srcd, onSuccess, onError);
// 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);
mediaRec.stopRecord();
}
}, 1000);
}
function onSuccess() {
alert('Uploaded Successfully');
}
// onError Callback
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Set audio position
//
function setAudioPosition(position) {
document.getElementById('audio_position').innerHTML = position;
}
</script>
</head>
<body>
<button onclick="recordAudio()">Record Audio</button>
<p id="media">Recording audio...</p>
<p id="audio_position"></p>
<br>
</body>
</html>
I am working on an Asp.Net MVC application where I am using signalR for real time database notifications
I am trying to create a proxy using the following script
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>JobStatus</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery.signalR-2.0.1.min.js"></script>
<script src="~/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var job = $.connection.jobHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblJobInfo');
$.ajax({
url: '../JobInfo/',
type: 'GET',
datatype: 'json',
success: function (data) {
if (data.length > 0) {
$tbl.empty();
$tbl.append(' <tr><th>ID</th><th>Name</th><th>Last Executed Date</th><th>Status</th></tr>');
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].LastExecutionDate.toString().substr(0,10) + '</td><td>' + data[i].Status + '</td></tr>');
}
$tbl.append(rows.join(''));
}
}
});
}
</script>
</head>
<body>
<div>
<table id="tblJobInfo" style="text-align:center;margin-left:10px"></table>
</div>
</body>
</html>
my SignalR Hub class is as follows
public class JobHub : Hub
{
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<JobHub>();
context.Clients.All.displayStatus();
}
}
but for some reason when I go to my view on the browser and look at the console it throws me follwing error
TypeError: $.connection is undefined
var job = $.connection.jobHub;
Not sure how to deal with this
Check if:
~/Scripts/jquery.signalR-2.0.1.min.js
is available and loading correctly
You can also reference it from cdn:
http://ajax.aspnetcdn.com/ajax/signalr/jquery.signalr-2.0.1.min.js
I have been trying my hand at node.js and socket.io, and following a tutorial. I keep getting an error from an application i am building. This is my server.js file:
var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {};
var chatServer = require('./lib/chat_server.js');
chatServer.listen(server);
//file doesn't exist
function send404(response) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('Error 404: resource not found.');
response.end();
}
//handles serving file data
function sendFile(response, filePath, fileContents) {
response.writeHead(
200,
{"content-type": mime.lookup(path.basename(filePath))}
);
response.end(fileContents);
}
//cache static files to memory
function serveStatic(response, cache, absPath) {
if (cache[absPath]) {
sendFile(response, absPath, cache[absPath]);
} else {
fs.exists(absPath, function(exists) {
if (exists) {
fs.readFile(absPath, function(err, data) {
if (err) {
send404(response);
}
else {
cache[absPath] = data;
sendFile(response, absPath, data);
}
});
}
else {
send404(response);
}
});
}
}
var server = http.createServer(function(request, response) {
var filePath = false;
if (request.url == '/') {
filePath = 'public/index.html';
}
else {
filePath = 'public' + request.url;
}
var absPath = './' + filePath;
serveStatic(response, cache, absPath);
});
server.listen(3001, function() {
console.log("Server listening on port 3001.");
});
This is my index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Chat</title>
<meta name="description" content="An interactive chat application using websockets.">
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<div id='content'>
<div id='room'></div>
<div id='room-list'></div>
<div id='messages'></div>
<form id='send-form'>
<input id='send-message' />
<input id='send-button' type='submit' value='Send'/>
<div id='help'>
Chat commands:
<ul>
<li>Change nickname: <code>/nick [username]</code></li>
<li>Join/create room: <code>/join [room name]</code></li>
</ul>
</div>
</form>
</div>
<script src="[localserver here]:3001/socket.io/socket.io.js" type="text/javascript"></script>
<script src="/javascripts/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="/javascripts/chat.js" type="text/javascript"></script>
<script src="/javascripts/chat_ui.js" type="text/javascript"></script>
</body>
</html>
Upon loading "[localserver here]:3001" from the browser, the index page appears with the ensuing CSS. But when i try an event, like sending a message, i get this error:
Error 404: resource not found.
I right-clicked and inspected element from my Chrome browser and got this two messages:
Failed to load resource: the server responded with a status of 404 (Not Found) "[localserver here]:3001/socket.io/socket.io.js"
Uncaught ReferenceError: io is not defined "[localserver here]:3001/javascripts/chat_ui.js:26"
This is line 26 from my chat_ui.js file:
var socket = io.connect('[localserver here]:3001');
$(document).ready(function() {
var chatApp = new Chat(socket);
socket.on('nameResult', function(result) {
var message;
if (result.success) {
message = 'You are now known as ' + result.name + '.';
} else {
message = result.message;
}
$('#messages').append(divSystemContentElement(message));
});
socket.on('joinResult', function(result) {
$('#room').text(result.room);
$('#messages').append(divSystemContentElement('Room changed.'));
});
socket.on('message', function (message) {
var newElement = $('<div></div>').text(message.text);
$('#messages').append(newElement);
});
socket.on('rooms', function(rooms) {
$('#room-list').empty();
for(var room in rooms) {
room = room.substring(1, room.length);
if (room != '') {
$('#room-list').append(divEscapedContentElement(room));
}
}
$('#room-list div').click(function() {
chatApp.processCommand('/join ' + $(this).text());
$('#send-message').focus();
});
});
setInterval(function() {
socket.emit('rooms');
}, 1000);
$('#send-message').focus();
$('#send-form').submit(function() {
processUserInput(chatApp, socket);
return false;
});
})
I have tried all sorts. Initially line 26 was var socket = io.connect(); and i changed it to the one above. I also changed the directory of socket.io.js in the index.html file from:
to
...as i thought this was the problem, but it is still giving me the same error.
Please how do i resolve this?
(PS - I am using Brackets as my IDE for node.js development. Also, i used "[localserver]" to indicate the localhost)
Try this:
<script type="text/javascript" src='http://localhost:3001/socket.io/socket.io.js'>
</script>
<script type="text/javascript">
var socket = io.connect('http://localhost:3001');
socket.on('connect',function(){
console.log("connect");
});
</script>
It must help you.
The line chatServer.listen(server); should be after you run your server.
chartServer is listening to the server but that one is not running yet.
Try to move this line:
chatServer.listen(server);
to the end of your script server.js
I am having trouble to get phonegap working properly. The phonegap function/objects don't seem to be working. Also push notifications don't work too even though I have included the plugin using the proper CLI command and have made sure that all the files are in the correct places according to the documentation. I have use javascript code from the PushNotifications plugin documentation so I assume it is correct also.
I have installed PhoneGap on Mac OS X 10.8.4 and created a new PhoneGap project using the CLI interface.
Then I wrote the HTML/CSS/JavaScript files for the app and placed them in the www directory.
I used the following command to build and run the application on my android device:
phonegap local run android
It worked fine and the application launched on my device. Everything worked fine.
Then I added some code that uses phonegap's functions/objects and tried to run it on android again.
The app ran fine again, but this time the following code did not execute:
alert(device.platform);
Also the PushNotifications code did not execute too due to an error (device is not defined)
I have tried to include cordova.js, phonegap.js, both of them at the same time or even none of them, but the result is still same.
I checked to see if the platforms/android/assets/www folder in the project directory contained the correct files, and it did. Both cordova.js and phonegap.js files were automatically added (phonegap build command adds both files for backward compatibility reasons, at least thats how I understood it).
So I am trying to figure out why device object is undefined even when phonegap.js file exists in the www folder and is included in the html file. I think if I can get the "alert(device.platform);" code working then the push notification code would work too, as it fails at the if statement that has to evaluate device.platform.
Here is the code for the index page:
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/index.css"/>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery-2.0.0.min.js"></script>
<script type="text/javascript" charset="utf-8" src="js/functions.js"></script>
<script src="js/fastclick.js"></script>
<script type="text/javascript" src="PushNotification.js"></script>
<script type="text/javascript" src="http://debug.build.phonegap.com/target/target-script-min.js#f997ffa0-5ed6-11e2-84ec-12313d1744da"></script>
<script type="text/javascript" charset="utf-8">
//*********************************************************
// Wait for Cordova to Load
//*********************************************************
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
//THE FOLLOWING CODE IS RESPONSIBLE FOR PUSH NOTIFICATIONS
var pushNotification;
alert(device.platform);
try {
pushNotification = window.plugins.pushNotification;
if (device.platform == 'android' || device.platform == 'Android') {
$("#app-status-ul").append('<li>registering android</li>');
pushNotification.register(successHandler, errorHandler, {"senderID":"hidden-by-me","ecb":"onNotificationGCM"}); // required!
} else {
$("#app-status-ul").append('<li>registering iOS</li>');
pushNotification.register(tokenHandler, errorHandler, {"badge":"true","sound":"true","alert":"true","ecb":"onNotificationAPN"}); // required!
}
}
catch(err) {
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
alert(txt);
}
//Rest of the code
updateData();
if (window.localStorage.getItem("default-school") == "infant") {
window.location.replace("infant.html");
} else
if (window.localStorage.getItem("default-school") == "junior") {
window.location.replace("junior.html");
};
}
// iOS
function onNotificationAPN(event) {
if (event.alert) {
navigator.notification.alert(event.alert);
}
if (event.sound) {
var snd = new Media(event.sound);
snd.play();
}
if (event.badge) {
pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
}
}
// Android
function onNotificationGCM(e) {
$("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>');
switch( e.event ) {
case 'registered':
if ( e.regid.length > 0 ) {
$("#app-status-ul").append('<li>REGISTERED -> REGID:' + e.regid + "</li>");
// Your GCM push server needs to know the regID before it can push to this device
// here is where you might want to send it the regID for later use.
console.log("regID = " + e.regID);
}
break;
case 'message':
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
if (e.foreground) {
$("#app-status-ul").append('<li>--INLINE NOTIFICATION--' + '</li>');
// if the notification contains a soundname, play it.
var my_media = new Media("/android_asset/www/"+e.soundname);
my_media.play();
}
else {
// otherwise we were launched because the user touched a notification in the notification tray.
if (e.coldstart) $("#app-status-ul").append('<li>--COLDSTART NOTIFICATION--' + '</li>');
else $("#app-status-ul").append('<li>--BACKGROUND NOTIFICATION--' + '</li>');
}
$("#app-status-ul").append('<li>MESSAGE -> MSG: ' + e.payload.message + '</li>');
$("#app-status-ul").append('<li>MESSAGE -> MSGCNT: ' + e.payload.msgcnt + '</li>');
break;
case 'error':
$("#app-status-ul").append('<li>ERROR -> MSG:' + e.msg + '</li>');
break;
default:
$("#app-status-ul").append('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>');
break;
}
}
function tokenHandler (result) {
$("#app-status-ul").append('<li>token: '+ result +'</li>');
// Your iOS push server needs to know the token before it can push to this device
// here is where you might want to send it the token for later use.
}
function successHandler (result) {
$("#app-status-ul").append('<li>success:'+ result +'</li>');
}
function errorHandler (error) {
$("#app-status-ul").append('<li>error:'+ error +'</li>');
}
</script>
</head>
<body onload="initFastButtons();init();">
<span id="fastclick">
<div id="main">
<ul id="app-status-ul">
<li>Push Plugin test</li>
</ul>
</div>
</span>
</body>
</html>
It would be really great if anyone could help me out on this one.
Which version of phonegap are you using?
If v3 then did you install the 'device' plugin?
$ phonegap local plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git
I was attempting to get this working in Phonegap Build for a long time and finally figured it out:
config.xml
<gap:plugin name="org.apache.cordova.device" /> <!-- Needed to use device.model (Not available until document deviceready event-->
javascript:
function deviceReady() {
alert(device.model);
}
document.addEventListener("deviceready", deviceReady, false);
However, I found out this object is not needed for the information i was looking for (device.model and device.version) because it was available in navigator.userAgent.
The version is the Android version number in the useragent string and the device model is right after "Android" in the useragent string.
I am trying to download an apk file on a button click using phonegap. Why does this code not work? Nothing happens when I click Download. Could someone point me in the right direction? Thanks.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script charset="utf-8" src = "jquery-1.10.1.min.js"></script>
<script charset="utf-8" src = "cordova-2.7.0.js"></script>
<script>
function foo()
{
var fileTransfer = new FileTransfer();
fileTransfer.download(
"http://samplewebsite.com/example.apk",
"file:///sdcard/example.apk",
function(entry) {
console.log("download complete: " + entry.fullPath);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
}
);
}
</script>
</head>
<body>
<button onclick="foo()">Download</button>
</body>
</html>
var fileTransfer = new FileTransfer();
var uri = encodeURI(url);
var filePath= "/sdcard/directory/file.extension";
fileTransfer.download(uri,filePath,
function(entry) {
//success
},
function(error) {
//failed
}
);
This worked for me
Your code works fine.
This seems stupid but have you tried to use alert() instead of console.log() in the callbacks?
If you are sure the callback code is not invoked try to run just the app created by the phonegap' create script and check that the device is ready before doing other tests.
just my 2c