How mediasource readystate changes its state - javascript

After going through the online documentation, I have written the code mentioned below. Whenever it is a small sized file it works well. But with bigger files i am getting the Error: Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable. This is because the mediasource.readystate has changed to close. I am not able to figure out which statement changes readystate from close to open and then back to close. I logged the readystate value at all places. It changes to open inside the mediacallback method. What triggers this change ??
WT = (function () {
var mediaSource = new MediaSource();
function fileSelected(evt) {
var video = document.getElementById("vid");
var file = evt.target.files[0];
if (file) {
var NUM_CHUNKS = 10000, i = 0;
var chunkSize = Math.ceil(file.size / NUM_CHUNKS);
console.log(mediaSource.readyState);
video.src = window.URL.createObjectURL(mediaSource);
console.log(mediaSource.readyState);
var queue = [];
var mediaCallback = function (e) {
console.log(mediaSource.readyState);
var sourceBuffer = mediaSource.addSourceBuffer('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
sourceBuffer.addEventListener('updateend', function() {
console.log("update end");
if (queue.length ) {
sourceBuffer.appendBuffer(queue.shift());
}
}, false);
(function readChunk(i) {
var reader = new FileReader();
reader.onload = function(et) {
var buff = new Uint8Array(et.target.result);
if(!sourceBuffer.updating && queue.length === 0) {
sourceBuffer.appendBuffer(buff);
} else {
queue.push(buff);
}
if (i == NUM_CHUNKS - 1) {
console.log("end of stream");
mediaSource.endOfStream();
} else {
if (video.paused) {
console.log("video puased");
video.play(); // Start playing after 1st chunk is appended.
}
readChunk(++i);
}
};
var startByte = chunkSize * i;
var chunk = file.slice(startByte, startByte + chunkSize);
reader.readAsArrayBuffer(chunk);
})(i);
}
mediaSource.addEventListener('sourceopen', mediaCallback, false);
mediaSource.addEventListener('sourceended', function(e) {
console.log('ended: mediaSource readyState: ' + this.readyState);
}, false);
mediaSource.addEventListener('sourceclose', function(e) {
console.log('closed: mediaSource readyState: ' + this.readyState);
}, false);
} else {
console.log("NO FILE SELECTED");
}
}
return {
init: function() {
console.log("Onclick");
if (window.File && window.FileReader && window.FileList && window.Blob) {
$("document").ready(function(){
$("#fileToUpload").on("change", fileSelected);
});
} else {
alert('The File APIs are not fully supported in this browser.');
}
}
}
})();
WT.init();

Related

JQuery FileReader onload not firing

I have a multiple file uploading. When I upload the images and binding to the model as follows not firing the FileReader onload function. It skip and fire remain
Here is my code
imageSelect: function (e) {
var dataModel = bindViewModel.selected.attachments;
var reader = new FileReader();
reader.onload = function () {
var uploadImg = new Image();
uploadImg.onload = function () {
for (var i = 0; i < e.files.length; i++) {
if (e.files[i].size < 1048576) {
var attachmentName = e.files[i].name;
var attachment = { id: i, citationId: bindViewModel.selected.id, attachmentName: attachmentName, attachmentUrl: reader.result };
dataModel.push(attachment);
if (dataModel[0].attachmentName == "" && dataModel[0].attachmentUrl == "") {
dataModel.splice($.inArray(dataModel[0], dataModel), 1);
}
uploadImg.src = reader.result;
reader.readAsDataURL(e.files[i].rawFile);
}
else {
app.ShowNotifications("Error", 'The ' + e.files[i].name + ' size greater than 1MB. \r\n Maximum allowed file size is 1MB.', "error");
}
}
};
};
}
Any one can have to help me?

'Debugging connection was closed. Reason: Render process gone.' while trying to upload big/multiple files using FileReader

I want to upload some files. If the file is smaller than 1gb, upload it entirely.
If the file is bigger than 1gb, upload it as segments of maximum 1gb each.
My code works correctly on small files, but when I try to upload bigger files, the browser crashes. Error "Debugging connection was closed. Reason: Render process gone."
The file that I was making tests with is 4,3 GB, and will start 5 XHR request.
What am I doing wrong?
let count = 0;
for (let url of this.urls) {
var start = 0 + (idx * 1000000000);
var stop = 0;
if (this.urls.length === 1)
stop = files[0].size;
else if (this.urls[this.urls.length - 1] == url)
stop = start + (files[0].size % 1000000000);
else
stop = start + 1000000000;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = (event) => {
if (reader.readyState === 2) {
this._httpService.xhrBlobPut(url, reader.result).subscribe(result => {
count += 1;
if (count == this.urls.length) {
this._storageService.postFile(this.appId, this.fileId, payload).subscribe(result => {
});
}
});
}
};
var blob = files[0].slice(start, stop + 1);
reader.readAsArrayBuffer(blob);
this.isUploaded = true;
idx += 1;
}
xhrBlobPut(url: string, body: any): Observable<any> {
return Observable.fromPromise(new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200 || xhr.status === 201) {
resolve(xhr.response)
} else {
reject(xhr.response)
}
}
}
xhr.open("PUT", url);
xhr.send(body);
}));
}

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__');

Can I open the URL automaticly when I scan with WebQR

I am a programmer and I just made a simple webapp, with webview in Android studio. I have everything working except one thing. I used the WebQR set from LazarSoft. In my webapp part I have a file called webqr.js (found beneath) with the following content.
What I am trying to do is when a QR-code is scanned I want to open the result (if it is an URL) automatic in the same browser window. Now it just shows only the result.
Any help would be much appreciated.
var gCtx = null;
var gCanvas = null;
var c=0;
var stype=0;
var gUM=false;
var webkit=false;
var moz=false;
var v=null;
var imghtml='<div id="qrfile"><canvas id="out-canvas" width="320" height="240"></canvas>'+
'<div id="imghelp">drag and drop a QRCode here'+
'<br>or select a file'+
'<input type="file" onchange="handleFiles(this.files)"/>'+
'</div>'+
'</div>';
var vidhtml = '<video id="v" autoplay></video>';
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
if(files.length>0)
{
handleFiles(files);
}
else
if(dt.getData('URL'))
{
qrcode.decode(dt.getData('URL'));
}
}
function handleFiles(f)
{
var o=[];
for(var i =0;i<f.length;i++)
{
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
gCtx.clearRect(0, 0, gCanvas.width, gCanvas.height);
qrcode.decode(e.target.result);
};
})(f[i]);
reader.readAsDataURL(f[i]);
}
}
function initCanvas(w,h)
{
gCanvas = document.getElementById("qr-canvas");
gCanvas.style.width = w + "px";
gCanvas.style.height = h + "px";
gCanvas.width = w;
gCanvas.height = h;
gCtx = gCanvas.getContext("2d");
gCtx.clearRect(0, 0, w, h);
}
function captureToCanvas() {
if(stype!=1)
return;
if(gUM)
{
try{
gCtx.drawImage(v,0,0);
try{
qrcode.decode();
}
catch(e){
console.log(e);
setTimeout(captureToCanvas, 500);
};
}
catch(e){
console.log(e);
setTimeout(captureToCanvas, 500);
};
}
}
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
function read(a)
{
var html="<br>";
if(a.indexOf("http://") === 0 || a.indexOf("https://") === 0)
html+="<a target='_blank' href='"+a+"'>"+a+"</a><br>";
html+="<b>"+htmlEntities(a)+"</b><br><br>";
document.getElementById("result").innerHTML=html;
}
function isCanvasSupported(){
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
}
function success(stream) {
if(webkit)
v.src = window.webkitURL.createObjectURL(stream);
else
if(moz)
{
v.mozSrcObject = stream;
v.play();
}
else
v.src = stream;
gUM=true;
setTimeout(captureToCanvas, 500);
}
function error(error) {
gUM=false;
return;
}
function load()
{
if(isCanvasSupported() && window.File && window.FileReader)
{
initCanvas(800, 600);
qrcode.callback = read;
document.getElementById("mainbody").style.display="inline";
setwebcam();
}
else
{
document.getElementById("mainbody").style.display="inline";
document.getElementById("mainbody").innerHTML='<p id="mp1">QR code scanner for HTML5 capable browsers</p><br>'+
'<br><p id="mp2">sorry your browser is not supported</p><br><br>'+
'<p id="mp1">try <img src="firefox.png"/> or <img src="chrome_logo.gif"/> or <img src="Opera-logo.png"/></p>';
}
}
function setwebcam()
{
document.getElementById("result").innerHTML="- scanning -";
if(stype==1)
{
setTimeout(captureToCanvas, 500);
return;
}
var n=navigator;
document.getElementById("outdiv").innerHTML = vidhtml;
v=document.getElementById("v");
if(n.getUserMedia)
n.getUserMedia({video: true, audio: false}, success, error);
else
if(n.webkitGetUserMedia)
{
webkit=true;
n.webkitGetUserMedia({video:true, audio: false}, success, error);
}
else
if(n.mozGetUserMedia)
{
moz=true;
n.mozGetUserMedia({video: true, audio: false}, success, error);
}
//document.getElementById("qrimg").src="qrimg2.png";
//document.getElementById("webcamimg").src="webcam.png";
document.getElementById("qrimg").style.opacity=0.2;
document.getElementById("webcamimg").style.opacity=1.0;
stype=1;
setTimeout(captureToCanvas, 500);
}
function setimg()
{
document.getElementById("result").innerHTML="";
if(stype==2)
return;
document.getElementById("outdiv").innerHTML = imghtml;
//document.getElementById("qrimg").src="qrimg.png";
//document.getElementById("webcamimg").src="webcam2.png";
document.getElementById("qrimg").style.opacity=1.0;
document.getElementById("webcamimg").style.opacity=0.2;
var qrfile = document.getElementById("qrfile");
qrfile.addEventListener("dragenter", dragenter, false);
qrfile.addEventListener("dragover", dragover, false);
qrfile.addEventListener("drop", drop, false);
stype=2;
}
Welcome to JavaScript, may you long prosper with its many uses!
As you are new to JavaScript, you may not know its Browser API, but fear not!
What you are looking for is window.open
Its syntax is simple:
window.open("http://example.com")
So, when you get the url from you qr decoder, all you have to do is window.open the URL, and viola, the window will appear in a new tab!
Now if you want to open in the same browser window, then you want to use
window.location.replace("http://example.com")
This will redirect the same tab, instead of a new one!
To implement this in your program, take a look at this read function:
function read(a) {
// If it's a URL, open in here
if(a.indexOf("http://") === 0 || a.indexOf("https://") === 0)
window.location.replace(a)
}
Hope I could help!

JavaScript upload progress bar with xhr.status error 500, but one file loads

I've got a problem with a script that is used to upload one or more multipart/form-data files.
On my client's server, when I try to upload more than one file, I receive:
xhr.status error 500;
The first file is uploaded okay, but I can't upload more than 1 file. On my server, everything works fine - there is no error 500.
I have searched the web for help, but I could only find information about server problems, such as: can not accept POST, GET, OPTIONS...
But it's working with one file - and I'm stuck.
I tried to upload the files one by one, but then my progress bar is flashing like....
Here is my code:
$(document).ready( function() {
$(".errorNotice").hide();
});
var form = document.getElementById('upload-form');
var ident = document.getElementById('ident');
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('submit');
var max = document.getElementById('max');
var formUrl = form.action;
function sleep(milliseconds) {
setTimeout(function(){ return true; }, milliseconds);
}
form.onsubmit = function(event) {
event.preventDefault();
uploadButton.innerHTML = 'Trwa ładowanie...';
$("#upload-form").fadeOut();
setTimeout(function() {
$("#progressBar").fadeIn();
}, 500);
var files = fileSelect.files;
var formData = new FormData();
if( files.length > max.value) {
if( max.value == 1) {
var text = max.value + ' zdjęcie';
}
else if( max.value >1 && max.value <= 4) {
var text = max.value + ' zdjęcia';
}
else {
var text = max.value + ' zdjęć';
}
$("#progressBar").find("p").html('Możesz dodać maksymalnie: ' + text);
setTimeout(function() {
$("#progressBar").hide();
$("#upload-form").fadeIn();
}, 5000);
return false;
}
if( files.length == 0 )
{
$("#progressBar").hide();
$("#upload-form").show();
}
formData.append('ident', ident.value);
formData.append('modules', 'true');
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image.*')) {
continue;
}
formData.append('objectPhoto[]', file, file.name);
formData.append(name, file, file.name);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', formUrl , true);
xhr.upload.addEventListener("progress", function(e) {
if(e.lengthComputable) {
var percentage = Math.round((e.loaded * 100) / e.total);
document.getElementById("bar").style.width = percentage + '%';
document.getElementById("percent").innerHTML = percentage + '%';
}
}, false);
xhr.onload = function () {
console.log(this.responseText);
if(this.responseText == "ok") {
document.getElementById("percent").innerHTML = "Zakończono";
document.getElementById("progressBar").style.display = "none";
document.getElementById("upload-form").style.display = "block";
} else {
$(".errorNotice").show();
$(".errorNotice .error-text").html(this.responseText);
}
if (xhr.status === 200) {
uploadButton.innerHTML = 'Wgraj';
} else {
$(".errorNotice").show();
$(".errorNotice .error-text").html("Wystąpił nieoczekiwany błąd o kodzie: " + xhr.status);
uploadButton.innerHTML = 'Wyślij';
}
};
xhr.send(formData);
return false;
};

Categories

Resources