Create blob url with javascript - javascript

I'm trying to create a web application for videos, I decided to start by configuring the videos, in case of problem, creating blob url for videos.
It turns out that I'm not sure what terms to use to search in google and the ones I used do not find anything very simple or straightforward.
I would like to know how I can create a blob url for videos and what would be the best way, since I have already seen topics using FileReader and MediaSource and some others, so I would like to know the simplest way to do this.
I'm testing on a direct html, without external libraries or external files.
var URL = this.window.URL || this.window.webkitURL;
var file = new Blob(["http://localhost/assets/mp4/video.mp4"],{"type" : "video\/mp4"});
var value = URL.createObjectURL(file);
$(document).ready(function(){
$('#MyVideo').attr('src',value);
});
Generates a blob link but does not load the video
Edit:
For further questions from beginners like me, I got the expected result with the script below:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/assets/mp4/video.mp4');
xhr.responseType = 'arraybuffer';
xhr.onload = function(e){
var blob = new Blob(([xhr.response]));
var url = URL.createObjectURL(blob);
document.getElementById('_video').src = url;
};

Related

Open downloaded file in another application (web-app)

I am building a web application (PWA) using Javascript. I want the application to automatically open downloaded files, such as PDF, DOCX, etc., in an external standard application such as Adobe Reader and Word.
Is there a function in Javascript that solves my problem?
At the moment, the application simply downloads the file to the device.
Unfortunately, I do not have much experience with Javascript, so I apologize if this is a stupid question.
XHR.responseType = 'blob';
XHR.onload = function() {
var data = this.response;
var a = document.createElement('a');
a.href = window.URL.createObjectURL(data);
a.download = fileName;
a.dispatchEvent(new MouseEvent('click'));
};

Javascrip service worker blob

I am trying to download a file in a service worker. The file came from a blob.
I already know that i can download a blob by doing this
var urlCreator = window.URL || window.webkitURL;
var blobURL = urlCreator.createObjectURL(blob, { type: "octet/stream" });
or by using something like FileSaver.js
But today, i am trying to "render" the bytes array of the blob in the page and force the browser to download the document.
Why ?
I am trying to do that because, some browser that i am trying to reach do not support url like "blob:https:......"
So i try to find a way to render the bytearrays of my blob directly in javascript.
I know that i can push headers with worker, but not sure that is the right strategie.
I also try something like that
var xhr = new XMLHttpRequest();
xhr.open('GET', obj.URL, false);
xhr.overrideMimeType("application/octet-stream");
//xhr.setRequestHeader("Accept", "application/octet-stream");
xhr.responseType = "arraybuffer";
xhr.onload = function (e) {
self.Response(xhr.response);
//if (this.status == 200) {
// var myBlob = this.response;
// // myBlob is now the blob that the object URL pointed to.
//}
};
xhr.send();
In my worker.js
ps: Please avoid to told me, send you base64 blob content to your server and send back the file to the browser, i would like to find a pure javascript solution.
Is it possible ?

Using Simple Webaudiorecorder.js in R/Shiny and posting the recording to the server

I am using WebAudioRecorder.js for making online recordings in an R Shiny app, see:
https://github.com/addpipe/simple-web-audio-recorder-demo
As a format, I chose the wave format, and in the JavaScript code, the recording is obtained as a blob. I would like the program to save this blob on the server without any dialog.
Here, you shouldn't set the hole filePath in javascript, you should give it a filename and then php should put it in the correct folder.
function uploadWaveBlob (blob, encoding) {
var xhr = new XMLHttpRequest();
var formData = new FormData();
var fileName = Date().toISOString() + '.' + encoding;
formData.append("Wav", blob, fileName);
xhr.open('POST', uploadUrl);
xhr.onload = function () {
console.log('xhr complete');
};
xhr.send(formData);
}
imagine if i would upload something to like /etc/hosts or something
The following site gives code that shows how to upload a blob to the server:
https://gist.github.com/primaryobjects/d6cdf5d31242a629b0e4cda1bfc4bff9
The complete solution is available at:
https://github.com/heeringa0/simple-web-audio-recorder
and shows how to integrate the Simple WebAudioRecorder.js in an R Shiny app where the recording is saved to the server.

reading an object URL produced in a worker with IE

I have a webworker that is producing a CSV for downloading, and to conserve memory I only have it return the URL it produces from teh blob..
My worker code looks something like::
var blob = new Blob([ResultOfSomeWork()],{type:'text/csv'});
URL.createObjectURL(blob);
self.postMessage({url:blob.url});
My goal is to just be able to download it in firefox and chrome this is very easy as I can just set up an invisible <a> and have it be clicked to download it.
For IE10 I want to use msSaveBlob but I need a blob which I don't want to transfer.
How can I download a object dataurl in IE10?
So I found a solution that works. Apparently, I can XHR and read the content back in my main thread.
worker.onmessage = function(event){
var url = event.data.url;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType='blob';
xhr.onload = function(){
msSaveBlob(xhr.response, fileName +'.csv');
};
xhr.send();
}
While this feels extremely complicated it works well in practice and is really fast.

How to get the size and duration of an mp3 file?

I need to calculate the total length of an mp3 file.
Currently I am using a PHP class which I found # http://www.zedwood.com/article/php-calculate-duration-of-mp3.
This is working perfectly if the mp3 file in same server.
but if I have a URL from other site it throwing error. Please help me.
Is there any JavaScript J-Query function to get the length of the mp3 file
<?php include("mp3.class.php");
$f = 'http://cdn.enjoypur.vc/upload_file/5570/5738/5739/7924/Blue%20Eyes%20-%20Yo%20Yo%20Honey%20Singh%20(PagalWorld.com)%20-192Kbps%20.mp3';
$m = new mp3file($f);
$a = $m->get_metadata();
if ($a['Encoding']=='Unknown')
echo "?";
else if ($a['Encoding']=='VBR')
print_r($a);
else if ($a['Encoding']=='CBR')
print_r($a);
unset($a);
?>
Here's how you can get mp3 duration using Web Audio API:
const mp3file = 'https://raw.githubusercontent.com/prof3ssorSt3v3/media-sample-files/master/doorbell.mp3'
const audioContext = new (window.AudioContext || window.webkitAudioContext)()
const request = new XMLHttpRequest()
request.open('GET', mp3file, true)
request.responseType = 'arraybuffer'
request.onload = function() {
audioContext.decodeAudioData(request.response,
function(buffer) {
let duration = buffer.duration
console.log(duration)
document.write(duration)
}
)
}
request.send()
There is actually a library that can run at client-side, attempting to fetch just enough of the MP3 to read the ID3 tags:
http://github.com/aadsm/JavaScript-ID3-Reader
or
Try
HTML File API.
http://lostechies.com/derickbailey/2013/09/23/getting-audio-file-information-with-htmls-file-api-and-audio-element/
Perhaps the simplest solution is to use the audio html element to get the time duration and to obtain the size directly from the file returned by the FileReader object. A code example of this approach is shown below.
One down side of this and all the other solutions presented so far is the 10-20 second delay it takes for the audio tag's durationchanged event to fire when loading large, eg > 200MB files. Clearly there is a faster way to get this info because the duration is shown immediately when the file is entered into the browser as a file:///.... URL.
function checkMp3SizeAndDuration()
{
var files = document.getElementById('upload-file').files;
var file = files[0];
if (file.size > MAX_FILE_SIZE) {
return;
}
var reader = new FileReader();
var audio = document.createElement('audio');
reader.onload = function (e) {
audio.src = e.target.result
audio.addEventListener('durationchange', function() {
console.log("durationchange: " + audio.duration);
},false);
audio.addEventListener('onerror', function() {
alert("Cannot get duration of this file.");
}, false);
};
reader.readAsDataURL(file);
});
Having not been able to find something that was fast and didn't require a bunch of extra boilerplate code, I tweaked an existing server side javascript utility to run directly in the browser. Demo code is available at: https://github.com/eric-gilbertson/fast-mp3-duration
A Famous and Very SPI that you can use MP3 SPI
and the code is also very simple
File file = new File("filename.mp3");
AudioFileFormat baseFileFormat = AudioSystem.getAudioFileFormat(file);
Map properties = baseFileFormat.properties();
Long duration = (Long) properties.get("duration");
Use getID3() PHP library that works for VBR files as well.
This link help you sourceforge.net.
It's very much active in development.

Categories