webrtc store video and audio file separately - blob

I am want to store video with audio and and only audio file separately, however i am able to save video with audio, how do i save only audio as a 2nd file, below is js code
var listOfFilesUploaded = [];
function uploadToServer(recordRTC, callback) {
var blob = recordRTC instanceof Blob ? recordRTC : recordRTC.blob;
var fileType = blob.type.split('/')[0] || 'audio';
var fileName = (Math.random() * 1000).toString().replace('.', '');
if (fileType === 'audio') {
fileName += '.' + (!!navigator.mozGetUserMedia ? 'ogg' : 'wav');
} else {
fileName += '.webm';
}
// create FormData
var formData = new FormData();
formData.append(fileType + '-filename', fileName);
formData.append(fileType + '-blob', blob);
callback('Uploading ' + fileType + ' recording to server.');
makeXMLHttpRequest('save.php', formData, function(progress) {
if (progress !== 'upload-ended') {
callback(progress);
return;
}
Requirements:
1. Store Video along with the voice - which is working through below code
2. Store Audio file separately - Not able to figure out how to do it through below code.

Related

Large file upload for office 365(StartUpload,ContinueUpload,FinishUpload) not working as expected - SharePoint

When I am trying to upload large file using 3 new methods (StartUpload, ContinueUpload, FinishUpload) by uploading chunks of file then final uploaded file is corrupt file and size is also greater than actual file. I have used Rest API to upload large files.
Steps followed are as follows:-
Create HTML for input file.
<input name="FileUpload" type="file" id="uploadInput" className="inputFile" multiple="false" onchange="upload(this.files[0])" />
Below method is start point of code:
Creating Global variable for siteurl
var Tasks = {
urlName: window.location.origin + "/",
siteName: '/sites/ABC',
};
Calling Upload() method
First Create Dummy File with size 0 in folder to continue with large file upload.
Create FileReader object and then start creating chunks of file with 3 parameters(offset,length,method(i.e. start/continue/finishupload)) and push chunks into an array.
Creating unique id for upload i.e. uploadID
Calling UploadFile method
function upload(file) {
var docLibraryName = "/sites/ABC/Shared Documents";
var fileName = $("#uploadInput").val().replace(/C:\\fakepath\\/i, '');
var folderName = "";
createDummaryFile(docLibraryName, fileName, folderName)
var fr = new FileReader();
var offset = 0;
var total = file.size;
var length = 1000000 > total ? total : 1000000;
var chunks = [];
fr.onload = evt => {
while (offset < total) {
if (offset + length > total)
length = total - offset;
chunks.push({
offset,
length,
method: getUploadMethod(offset, length, total)
});
offset += length;
}
for (var i = 0; i < chunks.length; i++)
console.log(chunks[i]);
if (chunks.length > 0) {
const id = getGuid();
uploadFile(evt.target.result, id, docLibraryName, fileName, chunks, 0);
}
};
fr.readAsArrayBuffer(file);
}
function createDummaryFile(libraryName, fileName, folderName) {
return new Promise((resolve, reject) => {
var endpoint = Tasks.urlName + Tasks.siteName + "/_api/web/GetFolderByServerRelativeUrl('" + libraryName + "/" + folderName + "')/Files/add(url=#TargetFileName,overwrite='true')?" +
"&#TargetFileName='" + fileName + "'";
var url;
const headers = {
"accept": "application/json;odata=verbose"
};
performUpload(endpoint, headers, libraryName, fileName, folderName, convertDataBinaryString(0));
});
}
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
function getGuid() {
return (S4() + S4() + "-" + S4() + "-4" + S4().substr(0, 3) + "-" + S4() + "-" + S4() + S4() + S4()).toLowerCase();
}
//check position for selecting method
function getUploadMethod(offset, length, total) {
if (offset + length + 1 > total) {
return 'finishupload';
} else if (offset === 0) {
return 'startupload';
} else if (offset < total) {
return 'continueupload';
}
return null;
}
Upload file method
Convert arraybuffer to blob chunks to start uploading file
Start actual file chunks upload using methods and offset of 1mb we created earlier (uploadFileChunk method)
Start loop for chunk and call same method
function uploadFile(result, id, libraryPath, fileName, chunks, index) {
const data = convertFileToBlobChunks(result, chunks[index]);
var response = uploadFileChunk(id, libraryPath, fileName, chunks[index], data);
index += 1;
if (index < chunks.length)
uploadFile(result, id, libraryPath, fileName, chunks, index, chunks[index].offset);
}
function convertFileToBlobChunks(result, chunkInfo) {
var arrayBuffer = chunkInfo.method === 'finishupload' ? result.slice(chunkInfo.offset) : result.slice(chunkInfo.offset, chunkInfo.offset + chunkInfo.length);
return convertDataBinaryString(arrayBuffer);
}
function convertDataBinaryString(data) {
var fileData = '';
var byteArray = new Uint8Array(data);
for (var i = 0; i < byteArray.byteLength; i++) {
fileData += String.fromCharCode(byteArray[i]);
}
return fileData;
}
UploadFileChunk method to actually start uploading file chunks)
Form string if startupload then no fileoffset and if continueupload and finishupload then it will have fileoffset.
Call performupload method to start uploading using rest api
function uploadFileChunk(id, libraryPath, fileName, chunk, data) {
new Promise((resolve, reject) => {
var offset = chunk.offset === 0 ? '' : ',fileOffset=' + chunk.offset;
var folderName = "";
var endpoint = Tasks.urlName + Tasks.siteName + "/_api/web/getfilebyserverrelativeurl('" + libraryPath + "/" + fileName + "')/" + chunk.method + "(uploadId=guid'" + id + "'" + offset + ")";
const headers = {
"Accept": "application/json; odata=verbose",
"Content-Type": "application/octet-stream"
};
performUpload(endpoint, headers, libraryPath, fileName, folderName, data);
});
}
function performUpload(endpoint, headers, libraryName, fileName, folderName, fileData) {
new Promise((resolve, reject) => {
var digest = $("#__REQUESTDIGEST").val();
$.ajax({
url: endpoint,
async: false,
method: "POST",
headers: headers,
data: fileData,
binaryStringRequestBody: true,
success: function(data) {},
error: err => reject(err.responseText)
});
});
}
Please suggest why file uploaded is corrupted and having size less or greater than actual file?
Thanks in advance.
I had the same problem with this code. I changed convertFileToBlobChunks to just return the ArrayBuffer.
function convertFileToBlobChunks(result, chunkInfo) {
var arrayBuffer = chunkInfo.method === 'finishupload' ?
result.slice(chunkInfo.offset) : result.slice(chunkInfo.offset, chunkInfo.offset + chunkInfo.length);
return arrayBuffer;
}
I also removed "Content-Type": "application/octet-stream" from the header.
After doing that it uploaded fine.

Sending audio file created with RecordRTC to my server

I am new to working with Javascript, PHP, and with servers generally. I am working on a web page that will record audio from the user and save it to my server, using RecordRTC. I'm a bit confused about the XMLHttpRequest portion - how do I alter the following code to send to my server instead of the webrtc server?
function uploadToServer(recordRTC, callback) {
var blob = recordRTC instanceof Blob ? recordRTC : recordRTC.blob;
var fileType = blob.type.split('/')[0] || 'audio';
var fileName = (Math.random() * 1000).toString().replace('.', '');
if (fileType === 'audio') {
fileName += '.' + (!!navigator.mozGetUserMedia ? 'ogg' : 'wav');
} else {
fileName += '.webm';
}
// create FormData
var formData = new FormData();
formData.append(fileType + '-filename', fileName);
formData.append(fileType + '-blob', blob);
callback('Uploading ' + fileType + ' recording to server.');
makeXMLHttpRequest('https://webrtcweb.com/RecordRTC/', formData, function(progress) {
if (progress !== 'upload-ended') {
callback(progress);
return;
}
var initialURL = 'https://webrtcweb.com/RecordRTC/uploads/';
callback('ended', initialURL + fileName);
listOfFilesUploaded.push(initialURL + fileName);
});
}
Via my web hosting provider, I'm using an Apache server, phpMyAdmin, and a mySQL database. Do I just replace
makeXMLHttpRequest(https://webrtcweb.com/RecordRTC/
with "https://mywebsite.com" and replace
var initialURL = 'https://webrtcweb.com/RecordRTC/uploads/';
with the path to the file I created to hold these audio files (https://mywebsite.com/uploads)? Then set permissions for that folder to allow public write capabilities (this seems unsafe, is there a good method)?
This is the makeXMLHttpRequest function:
function makeXMLHttpRequest(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback('upload-ended');
}
};
request.upload.onloadstart = function() {
callback('Upload started...');
};
request.upload.onprogress = function(event) {
callback('Upload Progress ' + Math.round(event.loaded / event.total * 100) + "%");
};
request.upload.onload = function() {
callback('progress-about-to-end');
};
request.upload.onload = function() {
callback('progress-ended');
};
request.upload.onerror = function(error) {
callback('Failed to upload to server');
console.error('XMLHttpRequest failed', error);
};
request.upload.onabort = function(error) {
callback('Upload aborted.');
console.error('XMLHttpRequest aborted', error);
};
request.open('POST', url);
request.send(data);
}
Please make sure that your PHP server is running top over SSL (HTTPs)
Create a directory and name it uploadFiles
Create a sub-directory and name it uploads
Structure of the directories:
https://server.com/uploadFiles -> to upload files
https://server.com/uploadFiles/uploads -> to store files
index.php
Now create or upload following index.php file on this path: https://server.com/uploadFiles
<?php
// File Name: "index.php"
// via https://github.com/muaz-khan/RecordRTC/tree/master/RecordRTC-to-PHP
foreach(array('video', 'audio') as $type) {
if (isset($_FILES["${type}-blob"])) {
echo 'uploads/';
$fileName = $_POST["${type}-filename"];
$uploadDirectory = 'uploads/'.$fileName;
if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $uploadDirectory)) {
echo(" problem moving uploaded file");
}
echo($fileName);
}
}
?>
Why sub-directory?
Nested directory uploads will be used to store your uploaded files. You will get URLs similar to this:
https://server.com/uploadFiles/uploads/filename.webm
Longer file upload issues:
https://github.com/muaz-khan/RecordRTC/wiki/PHP-Upload-Issues
upload_max_filesize MUST be 500MB or greater.
max_execution_time MUST be at least 10800 (or greater).
It is recommended to modify php.ini otherwise create .htaccess.
How to link my own server?
Simply replace https://webrtcweb.com/RecordRTC/ with your own URL i.e. https://server.com/uploadFiles/.

Save an image from URL, store on device, and open image successfully in RN

I'm having difficulty fetching an image from a url, storing the image on a device, and opening/viewing it successfully.
I am able to fetch the image successfully (I believe)
I transform the image into base64 using Buffer (npm buffer) and save it to the device using react-native-fs. I'm not sure the Buffer transformation is needed. I can stat the image and everything looks fine. When I use a FileManager application I downloaded and I click on the file the image is blank.
let response = await axios.request({
url: imgUrl
});
let idxStart = imgUrl.lastIndexOf('/');
let idxEnd = imgUrl.lastIndexOf('.');
let filename = imgUrl.substring(idxStart + 1, idxEnd) + '.jpg';
let path = RNFS.DocumentDirectoryPath + `/${filename}`
let base64data = new Buffer(response.data).toString('base64');
RNFS.writeFile(RNFS.PicturesDirectoryPath + '/' + filename, base64data, 'base64').then(() => {
RNFS.stat(path).then(info => {
console.log(info);
});
RNFS.readFile(RNFS.PicturesDirectoryPath + '/' + filename, 'base64').then(data => {
// console.log('data:', data);
});
} ,error => {
console.log('error writing file:', error)
}).catch(error => { console.log('error:', error)});
If anybody could provide a simple working example that'd be AWESOME!

Titanium - Get image file from filesystem on Android

I have a problem getting an image from filesystem. On iOS works fine.
First of all, I save a remote image in the filesystem with this function:
img.imagen = url from the remote image (e.g. http://onesite.es/img2.jpeg)
function descargarImagen(img, callback){
var path = img.imagen;
var filename = path.split("/").pop();
var xhr = Titanium.Network.createHTTPClient({
onload: function() {
// first, grab a "handle" to the file where you'll store the downloaded data
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, filename);
f.write(this.responseData); // write to the file
Ti.API.debug("-- Imagen guardada: " + f.nativePath);
callback({path: f.nativePath});
},
timeout: 10000
});
xhr.open('GET', path);
xhr.send();
}
Now, I want to share this image creating an Android Intent:
args.image = f.nativePath(in the previous function)
var intent = null;
var intentType = null;
intent = Ti.Android.createIntent({
action: Ti.Android.ACTION_SEND
});
// add text status
if (args.status){
intent.putExtra(Ti.Android.EXTRA_TEXT, args.status);
}
// change type according to the content
if (args.image){
intent.type = "image/*";
intent.putExtraUri(Ti.Android.EXTRA_STREAM, args.image);
}else{
intent.type = "text/plain";
intent.addCategory(Ti.Android.CATEGORY_DEFAULT);
}
// launch intent
Ti.Android.currentActivity.startActivity(Ti.Android.createIntentChooser(intent, args.androidDialogTitle));
What I'm doing wrong?

Example code to use GridFS using mongoskin to upload file from form

I am using mongoskin to connect mongodb in my project. Now I have requirement to use GridFs to upload images, audio etc. I have one HTML form to upload these files.
I tried to find out example code to upload file using mongoskin however could't find any good one.
Please help.
After spending many hours; I am able to use mongoskin to upload file to Gridfs. Not sure if this is perfect code however sharing it here because I couldn't find any single working code on searching Google :-)
https://github.com/dilipkumar2k6/gridfs-mongoskin
var DBModule = require('./DBModule.js');
var Grid = require('gridfs-stream');
var mongoskin = require('mongoskin');
//Upload file to server and also update the database
exports.uploadContent = function (req, res) {
console.log('Calling uploadFile inside FileUploadService');
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
console.log('uploadFile after busboy fieldname: ' + fieldname + ", file : " + file + ", filename : " + filename);
// make sure the db instance is open before passing into `Grid`
var gfs = Grid(DBModule.db, mongoskin);
//Get metadata var host = req.headers['host'];
var metadata = {contentType: mimetype};
var writestream = gfs.createWriteStream({filename: filename, metadata: metadata});
file.pipe(writestream);
writestream.on('close', function (file) {
// return URL to acces the uploaded content
var path = "contents/" + file._id;
res.json({"path": path});
});
writestream.on('error', function (err) {
log.error({err: err}, 'Failed to upload file to database');
res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
res.json({error: err});
});
});
};
//view file from database
exports.previewContent = function (req, res) {
var contentId = new DBModule.BSON.ObjectID(req.params.contentid);
console.log('Calling previewFile inside FileUploadService for content id ' + contentId);
var gs = DBModule.db.gridStore(contentId, 'r');
gs.read(function (err, data) {
if (!err) {
//res.setHeader('Content-Type', metadata.contentType);
res.end(data);
} else {
log.error({err: err}, 'Failed to read the content for id ' + contentId);
res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
res.json({error: err});
}
});
};
Try this to store the data using gridfs (by default uses mongoskin). It worked for me.
var ObjectID = require('mongodb').ObjectID,
GridStore = require('mongodb').GridStore;
exports.saveMedia = function(db, media, next) {
console.log(media)
db.open(function (err, db) {
// Create a file and open it
var gridStore = new GridStore(db, new ObjectID(), "w");
gridStore.open(function (err, gridStore) {
// Write some content to the file
gridStore.write(new Buffer(media), function (err, gridStore) {
// Flush the file to db
gridStore.close(function (err, fileData)
//returns filename
next(null, fileData)
});
});
});
});
}