I have been looking around for days now :( so really needs your help.
what i am developing is an application that downloads images and videos and display them in full screen.
for the images all is good.
But when playing videos a got this image some times and the video doesn't play.
This my code for downloading:
download(URL, fileName, callback) {
var folderName = "serverMediaDir";
var uri = encodeURI(URL);
window.requestFileSystem(
LocalFileSystem.PERSISTENT,
0,
function (fileSystem) {
var directoryEntry = fileSystem.root; // to get root path of directory
directoryEntry.getDirectory(
folderName,
{
create: true,
exclusive: false
},
function (parent) {
// Directory created successfuly
var filename = fileSystem.root.toURL() + folderName + "/" + fileName;
console.log("Directory created successfuly: " + filename);
var fileTransfer = new FileTransfer();
fileTransfer.download(
uri,
filename,
function (entry) {
// download success
var path = entry.toURL(); //**THIS IS WHAT I NEED**
console.log("Download Completed: " + entry.fullPath);
callback(null, filename, entry);
},
function (error) {
callback(error, null);
} // irrelevant download error
);
},
function (error) {
//Error while creating directory
callback(error, null);
}
);
}, function (error) {
callback(error, null);
} // irrelevant request fileSystem error
);
}
and after that i save the videos and images full paths into an array that i use to display them.
This is how i play them:
vid: function () {
var self = this;
//Accepts any number of ‘src‘ to a same video ('.mp4', '.ogg' or '.webm')
var el = document.createElement("video");
// var source = document.createElement("source");
/*for (var i = 0; i < arguments.length; i++) {
source.src = arguments[i];
// source.type = "video/" + arguments[i].split(".")[arguments[i].split(".").length - 1];
el.appendChild(source);
}*/
el.src = arguments[0];
el.onplay = function () {
clearInterval(window.sliding);
};
el.onended = function () {
window.sliding = setInterval(self.rotateImages, self.mediaUnitDuration * 1000);
self.rotateImages();
};
return el;
},
rotateMedias: function () {
var self = this;
if (self.newMedia) {
self.galleryArray = [];
if (self.mediaServer.length === 0) {
self.galleryArray.push(self.img(require(window.display.toUpperCase() ==='H'? '~/assets/H.jpg':'~/assets/V.jpg')))
}
for (var i = 0; i < self.mediaServer.length; i++) {
if (self.mediaServer[i].type.toLowerCase() === "video" && self.mediaServer[i].status) {
var obj = {};
obj = self.vid(self.mediaServer[i].path);
} else if (self.mediaServer[i].type.toLowerCase() === "image" && self.mediaServer[i].status) {
var obj = {};
obj = self.img(self.mediaServer[i].path);
}
self.galleryArray.push(obj);
}
self.newMedia = false;
}
$("#slideShow").fadeOut("slow");
setTimeout(function () {
self.curImg = self.curImg < self.galleryArray.length - 1 ? self.curImg + 1 : 0;
document.getElementById("slideShow").innerHTML = "";
self.galleryArray[self.curImg].style.width = "100%";
self.galleryArray[self.curImg].style.height = "100%";
self.galleryArray[self.curImg].style.margin = "0px";
document.getElementById("slideShow").appendChild(self.galleryArray[self.curImg]);
if (self.galleryArray[self.curImg].tagName.toLowerCase() === "video") {
self.galleryArray[self.curImg].play();
}
$("#slideShow").fadeIn("slow");
}, 500);
}
What i did try as a solution is to change the dir in which i store the files (cordova.file.applicationDirectory|dataDirectory|externalApplicationStorageDirectory...) and tried them public and private also but not working also.
Also i tried both protocol file:/// and cdvfile://localhost
I use :
cordova 10.0.0
cordova-plugin-file-transfer 1.7.1
cordova-plugin-file 6.0.2
And runing the app on X96mini box with android 7.1.2
After a lot of testing i find that it is a box bug (the application work on many others android devices with different versions). Thnx god, i found this plugin so i use it and it works fine with some work arounds for sure.
Related
I have been searching the net and testing for hours now but I could not pinpoint what the error is. So, I am looking for your kind help here. I followed step by step multiple files upload tutorial with the drag & drop functionality but I got the error message as mentioned in the title (and the line of code that throws the error is xmlhttp.send(data); ).
File upload.js has this function:
(function(o) {
"use strict";
var ajax, getFormData, setProgress;
ajax = function(data) {
var xmlhttp = new XMLHttpRequest();
var uploaded;
xmlhttp.addEventListener('readystatechange', function() {
if (this.readyState === 4) {
if(this.status === 200){
uploaded = JSON.parse(this.response);
if(typeof o.options.finished === 'function'){
o.options.finished(uploaded);
}
} else {
if(typeof o.options.error === 'function'){
o.options.error();
}
}
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source) {
var data = new FormData();
var i;
for(i = 0; i < source.length; i = i + 1) {
data.append('files[]', source[i]);
}
return data;
};
o.uploader = function(options) {
o.options = options;
if(o.options.files !== undefined) {
ajax(getFormData(o.options.files));
}
};
}());
and the global.js file has this code:
(function() {
"use strict";
var dropZone = document.getElementById('drop-zone');
var uploadsFinished = document.getElementById('uploads-finished');
var startUpload = function(files) {
app.uploader({
files: files,
Processor: 'upload.php',
finished: function(data){
var x;
var uploadedElement;
var uploadedAnchor;
var uploadStatus;
for (x = 0; x < data.length; x = x + 1) {
currFile = data[x];
uploadedElement = document.createElement('div');
uploadedElement.className = 'uploaded-console-upload';
uploadedAnchor = document.getElementById('a');
uploadedAnchor.textContent = currFile.name;
if(currFile.uploaded) {
uploadedAnchor.href = 'uploads/' + currFile.file;
}
uploadedStatus = document.createElement('span');
uploadedStatus.textContent = currFile.uploaded ? 'uploaded' : 'Failed';
uploadedElement.appendChild(uploadedAnchor);
uploadedElement.appendChild(uploadedStatus);
uploadsFinished.appendChild(uploadedElement);
}
uploadsFinished.className = '';
},
error: function() {
//console.log('There was an error');
}
});
};
//Standard form upload
document.getElementById('standard-upload').addEventListener('click', function(e) {
var standardUploadFiles = document.getElementById('standard-upload-files').files;
e.preventDefault();
startUpload();
});
//Drop funtionality
dropZone.ondrop = function(e){
e.preventDefault();
this.className = 'upload-console-drop';
startUpload(e.dataTransfer.files);
};
dropZone.ondragover = function() {
this.className = 'upload-console-drop drop';
return false;
};
dropZone.ondragleave = function() {
this.className = 'upload-console-drop';
return false;
};
}());
Any help to solve this problem would be greatly appreciated. Thank you.
o.options.processor was defined as Processor and when it was called back later in the code, it was referred to as processor (changing from Processor to processor) solved the case. Thank you guys with your comments that helped me to find the error.
Recently I want to start a project by piggyback someone's extension. I want to scope one of the image source (local variable, a base64 url) and then photo recognize it on the popup page. I keep getting error "imgb64.replace is not a function" or "imgb64" not defined.
like my title said, I want to scope the local variable in.in.inside a function (from backgound.js )and use it globally (or in popup.js). very new to this, please help guys.
// this is popup.js
chrome.runtime.getBackgroundPage(function(bg) {
bg.capture(window);
});
/// what I did
function img_find() {
var imgs = document.getElementsByTagName("img");
var imgSrcs = [];
for (var i = 0; i < imgs.length; i++) {
imgSrcs.push(imgs[i].src);
}
return imgSrcs;
}
var imgb64 = img_find();
try {
const app = new Clarifai.App({
apiKey: 'mykey'
});
}
catch(err) {
alert("Need a valid API Key!");
throw "Invalid API Key";
}
// Checks for valid image type
function validFile(imageName) {
var lowerImageName = imageName.toLowerCase();
return lowerImageName.search(/jpg|png|bmp|tiff/gi) != -1;
}
var imageDetails = imgb64.replace(/^data:image\/(.*);base64,/, '');
console.log(imageDetails)
app.models.predict("e466caa0619f444ab97497640cefc4dc", {base64:
imageDetails}).then(
function(response) {
// do something with response
},
function(err) {
// there was an error
}
);
/// end what I did
below is background.js, I think what I need is the local var img.src, thats all.
function capture(popup) {
function callOnLoad(func) {
popup.addEventListener("load", func);
if (popup.document.readyState === "complete") {
func();
}
}
crxCS.insert(null, { file: "capture.js" }, function() {
crxCS.callA(null, "get", function(result) {
var scrShot, zm, bufCav, bufCavCtx;
function mkImgList() {
for (var i = 0; i < result.vidShots.length; i++) {
var img = new popup.Image();
img.onload = function() {
this.style.height = this.naturalHeight /
(this.naturalWidth / 400) + "px";
};
if (result.vidShots[i].constructor === String) {
img.src = result.vidShots[i];
} else {
bufCav.width = result.vidShots[i].width * zm;
bufCav.height = result.vidShots[i].height * zm;
bufCavCtx.drawImage(scrShot, -result.vidShots[i].left *
zm, -result.vidShots[i].top * zm);
img.src = bufCav.toDataURL('image/png');
////// maybe clarifai here ?
////end clarifai
}
popup.document.body.appendChild(img);
}
popup.onclick = function(mouseEvent) {
if (mouseEvent.target.tagName === "IMG") {
chrome.downloads.download({ url: mouseEvent.target.src,
saveAs: true, filename: "chrome_video_capture_" + (new Date()).getTime() +
".png" });
}
};
popup.onunload = function(mouseEvent) {
crxCS.callA(null, "rcy");
};
} /// end mkImgList
if (result.needScrShot) {
bufCav = popup.document.createElement("canvas");
bufCavCtx = bufCav.getContext("2d");
chrome.tabs.captureVisibleTab({ format: "png" },
function(dataUrl) {
scrShot = new Image();
scrShot.onload = function() {
chrome.tabs.getZoom(function(zoomFactor) {
zm = zoomFactor;
callOnLoad(function() {
mkImgList(zoomFactor);
});
});
};
scrShot.src = dataUrl;
});
} else if (result.vidShots.length) {
callOnLoad(mkImgList);
} else {
popup.document.body.appendChild(notFound);
}
}); // end crxCS.callA
}); // end crxCS.insert
} // end capture
Please help guys. :)
Trying to overcome the variable deficiencies of Flash's upload-to-server function - particularly not being able to track upload progress when cookies are required - I have decided to create a JavaScript function that does the upload and keeps track of the upload progress events.
Here it is:
window.you_animate = {
objToString: function(obj) {
var res = "{";
for (var str in obj) {
res += str +"=" + obj[str] + ",";
}
res += "}";
return res;
},
upload: function(url, _files, _data, progressCb, successCb, errorCb) {
alert("a,"+url);
var fd = new FormData(),
files = _files || [],
data = _data || [],
i;
alert("b");
for (i in data) {
fd.append(i, data[i]);
}
alert("c");
for (i = 0; i < files.length; i++) {
var file = files[i];
alert(i+"/"+files.length+" file= "+you_animate.objToString(file));
var blob = file.file || new Blob(file.data, {
type: file.type
});
alert("blob= "+you_animate.objToString(blob));
fd.append(file.name, blob);
}
alert("d");
var ajax_opts = {
type: 'POST',
url: url,
data: fd,
headers: {},
dataType: 'json',
contentType: false,
processData: false,
xhr: function() {
alert("1");
var xhr = new window.XMLHttpRequest();
if (xhr.upload) {
xhr.upload.addEventListener('progress', progressCb, false);
}
return xhr;
},
success: successCb || $.noop,
error: errorCb || $.noop
};
alert("2");
$.ajax(ajax_opts);
alert("3");
},
uploadProgress: {},
// => _data = base64 binary
uploadFromFlash: function(url, _files, _data) {
alert("0");
var uploadProcess = {};
var uploadProcessID = "id" + Math.floor(Math.random() * 1000000).toString();
you_animate.uploadProgress[uploadProcessID] = uploadProcess;
// workaround for Flash bug ("[]" in variable name)
for (var str in _data) {
_data["UploadCharacterForm["+str+"]"] = _data[str];
delete _data[str];
}
alert("01");
// base64 -> Blob-friendly stuff
for (i = 0; i < _files.length; i++) {
var file = _files[i];
var binary = atob(file.data);
var array = new Uint8Array(binary.length);
for( var i = 0; i < binary.length; ++i ) { array[i] = binary.charCodeAt(i) }
file.data = [array]; // NOTE : why "[array]" and not "array" ??
}
alert("02");
you_animate.upload(url, _files, _data,
function(progressEvent) {
uploadProcess.progressEvent = progressEvent;
},
function(successEvent) {
uploadProcess.successEvent = successEvent;
uploadProcess = null;
},
function(errorEvent) {
uploadProcess.errorEvent = errorEvent;
uploadProcess = null;
}
);
return uploadProcessID;
},
trackProcessID: function(id) {
return you_animate.uploadProgress[id];
},
destroyProcessID: function(id) {
delete you_animate.uploadProgress[id];
},
uploadForm: function(form, progressCb, successCb, errorCb) {
var $form = $(form),
action = $form.attr('action') + '?json';
var data = $form.serializeArray().reduce(function(prev, curr){
prev[curr.name] = curr.value; return prev;
}, {} );
var $files = $form.find('input[type=file]');
var files = [];
$files.each(function(index, node) {
if (node.files[0]) {
files.push({
name: node.name,
file: node.files[0]
});
}
});
you_animate.upload(action, files, data, progressCb, successCb, errorCb);
}
};
Question 1: the progress event differs between Chrome and Firefox. The first returns loaded & totalSize (among lots of other stuff), while Firefox returns loaded & total!!!
Is there somewhere a specification for the returned progress event?!
Question 2: Internet Explorer 8 crashes right after alert("0") ! Maybe it doesn't like "[ ]" in the following line:
_data["UploadCharacterForm["+str+"]"] = _data[str];
Anything to do about that?
I currently have a chrome packaged app that we have also ported to iPad, but I want to make it install-able using node-webkit (nw.js) and I need to abstract the chrome packaged app API for use with chrome.fileSystem. The code I am currently using to save is as follows.
var downloadFile = function (readUrl, next) {
var xhr = new XMLHttpRequest();
xhr.open('GET', readUrl);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
if (this.status == 200) {
var response = this.response;
var params = {
type : 'saveFile',
suggestedName : fileNameNoExtension,
//my code will inject the extension but in this case i just put in txt
accepts : [{
extensions : ['.txt']
}
]
}
chrome.fileSystem.chooseEntry(params, function (writableFileEntry) {
debugger;
writableFileEntry.createWriter(function (writer) {
debugger;
writer.onwriteend = function (e) {
return next(null)
};
writer.onerror = function (e) {};
writer.write(new Blob([response], {
type : 'application/octet-stream'
}));
});
});
} else {
//alert
}
};
xhr.onprogress = function (evt) {
if (evt.lengthComputable) {
console.log('progress: ' + Math.round(evt.loaded * 100 / evt.total));
}
}
xhr.addEventListener("error", function () {
return next('error')
}, false);
xhr.addEventListener("abort", function () {
return next('abort')
}, false);
xhr.send();
}
I have created a file that I am calling interop.js I load this script into my index.html and it will handle all of the chrome packaged app API calls for fileStorage if it's a nw.js project. If it's a chrome packaged app, then chrome will handle it's own API.
//if process is undefined then it is not an nw.js project and we can ignore the rest of the code;
if (typeof process == 'undefined') {}
//this is a nw.js project, spoof the chrome packaged app API
else {
var fs = require('fs')
chrome = new function () {
var fileSystem = {
//callback return readableFileEntry, which has a
chooseEntry : function (params, callback) {
if (params.type == 'openFile') {
//open file choose
chooseFile(params, function (files) {
//this is technically an html5 "filelist" we need to turn it into an array if there is more
//than one, and just return the single file if there isn't
if (!files) {
return callback(null)
}
async.map(files, function (file, cb) {
//normally chrome provides a 'readablefileentry' that will only give you the file
//asynchronously using the file() function
file.file = function (next) {
return next(this);
}
cb(null, file)
}, function (err, files) {
if (files.length > 1) {
return callback(files);
} else {
return callback(files[0]);
}
})
})
} else if (params.type == 'saveFile') {
chooseFile(params, function (files) {
var file = files[0];
debugger;
file.createWriter = function (next) {
var writer = {
write : function (blob) {
debugger;
var reader = new FileReader()
reader.readAsArrayBuffer(blob)
reader.addEventListener('loadend', function (e) {
var binary = new Uint8Array(reader.result)
debugger;
fs.writeFile(file.path, new Buffer(binary), function (err) {
//if the on error and writeend has been defined then callback, otherwise throw the error and log success
if (err && writer.onerror) {
writer.onerror(err)
} else if (err) {
throw err
} else if (writer.onwriteend) {
writer.onwriteend()
} else {
console.log('file was written but no callback was defined')
}
})
});
}
}
return next(writer)
}
return callback(file)
})
}
function chooseFile(params, next) {
var fileHtml = '<input type="file"'
debugger;
if (params.acceptsMultiple)
fileHtml += ' multiple';
if (params.accepts && params.accepts.length > 0 && params.accepts[0].extensions) {
fileHtml += ' accept="'
for (var i = 0; i < params.accepts[0].extensions.length; i++) {
if (i != 0)
fileHtml += ','
fileHtml += '.' + params.accepts[0].extensions[i]
}
fileHtml += '"'
}
if (params.suggestedName) {
fileHtml += ' nwsaveas="' + params.suggestedName + '"'
}
fileHtml += '>'
var chooser = $(fileHtml);
chooser.change(function (evt) {
debugger;
return next(chooser[0].files)
});
chooser.click();
}
}
}
return {
fileSystem : fileSystem,
}
};
}
I have to use ffmpeg in my project to convert an audio file from wav t mp3,pcm and vox. my project is javascript/php built can anyone direct me how to use ffmpeg.I've been reading a lot and now that it depends on the command lines.but where to write these command lines.If someone can show me a demo of how to use it i will thankful
I have found this function, but don't know how to give it the file to convert.
function getFFMPEGWorker() {
// regexps for extracting time from ffmpeg logs
var durationRegexp = /Duration: (.*?), /
var timeRegexp = /time=(.*?) /;
var duration;
var ffmpegWorker = new Worker('worker.js');
var durationLine;
ffmpegWorker.addEventListener('message', function(event) {
var message = event.data;
console.log(message.type);
if (message.type === "ready" && window.File && window.FileList && window.FileReader) {
// script loaded, hide loader
$('#loading').hide();
} else if (message.type == "stdout") {
console.log(message.data);
} else if (message.type == "stderr") {
console.log(message.data);
// try to extract duration
if (durationRegexp.exec(message.data)) {
duration = timeToSeconds(durationRegexp.exec(message.data)[1]);
}
// try to extract time
if (timeRegexp.exec(message.data)) {
var time = timeToSeconds(timeRegexp.exec(message.data)[1]);
if (duration) {
$("#progress").text("Progress: " + Math.floor(time / duration * 100) + "%");
$("#progress").show();
}
}
} else if (message.type == "done") {
var code = message.data.code;
console.log(message.data);
var outFileNames = Object.keys(message.data.outputFiles);
console.log(outFileNames);
if (code == 0 && outFileNames.length) {
var outFileName = outFileNames[0];
var outFileBuffer = message.data.outputFiles[outFileName];
var src = window.URL.createObjectURL(new Blob([outFileBuffer]));
$("#downloadLink").attr('href', src);
$("#download").show();
} else {
$("#error").show();
}
$("#converting").hide();
$("#progress").hide();
}
}, false);
return ffmpegWorker;
}
// create ffmpeg worker
var ffmpegWorker = getFFMPEGWorker();
var ffmpegRunning = false;
$('#convert').click(function() {
// terminate existing worker
if (ffmpegRunning) {
ffmpegWorker.terminate();
ffmpegWorker = getFFMPEGWorker();
}
ffmpegRunning = true;
// display converting animation
$("#converting").show();
$("#error").hide();
// hide download div
$("#download").hide();
// change download file name
var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
var outFileName = fileName.substr(0, fileName.lastIndexOf('.')) + "." + getOutFormat();
$("#downloadLink").attr("download", outFileName);
$("#downloadLink").text(outFileName);
var arguments = [];
arguments.push("-i");
arguments.push(fileName);
arguments.push("-b:a");
arguments.push(getBitrate());
switch (getOutFormat()) {
case "mp3":
arguments.push("-acodec");
arguments.push("libmp3lame");
arguments.push("out.mp3");
break;
case "wma":
arguments.push("-acodec");
arguments.push("wmav1");
arguments.push("out.asf");
break;
case "pcm":
arguments.push("-f");
arguments.push("s16le");
arguments.push("-acodec");
arguments.push("pcm_s16le");
arguments.push("out.pcm");
}
ffmpegWorker.postMessage({
type: "command",
arguments: arguments,
files: [
{
"name": fileName,
"buffer": fileBuffer
}
]
});
});