Convert base64 audio to file - javascript

I have an audio blob, I then run
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
var base64data = reader.result;
//log of base64data is "data:audio/ogg; codecs=opus;base64,GkX..."
}
Now I send this data to my server and all I'm trying to do is convert to an '.ogg' file (wav or mp3 preferred). The base64 works fine when passed to an HTML audio player.
On the server I tried
fs.writeFileSync('file.ogg', base64data);
I always get the file created however it never plays, what I'm I doing wrong please?

You have binary data encoded in base64 string here. First of all you need trim data url meta info. Then you can create binary buffer from base64 string and store it to file.
fs.writeFileSync('file.ogg', Buffer.from(base64data.replace('data:audio/ogg; codecs=opus;base64,', ''), 'base64'));

Related

Downloading image in Javascript creates corrupted file

I'm trying to download an image and write it to the disk in Javascript. The image will be delivered base64 encoded by the server. I'm then trying to decode the image, create a blob with that data and create a new URL object. The download itself works, but the output file will be corrupted and unusable. My code looks as follows:
jsonObject = JSON.parse(requestObject.getReturnData());
decoded = atob(jsonObject['DownloadFile']);
url = window.URL.createObjectURL(new Blob([decoded], { type: "image/png" }));
aElement = document.createElement('a');
aElement.style.display = 'none';
aElement.href = url;
aElement.download = 'download.' + jsonObject['DownloadType'];
document.body.appendChild(aElement);
aElement.click();
window.URL.revokeObjectURL(url);
I verified that jsonObject['DownloadFile'] contains the correct base64 representation of the image. However, it seems that there's an error when creating the blob, since its size is too big when looking at the debug console.

How to read large video files in JavaScript using FileReader?

I want the user of my website to be able to upload a potentially large video file to it using HTML‘s file input. The video should than be processed and played locally in the user‘s browser.
let fileInput = document.createElement("INPUT");
fileInput.setAttribute("type", "file");
fileInput.onChange = onFileSelected;
To read the video file uploaded by the user, I wanted to use a File Reader like this:
function onFileSelected(e) {
// The file uploaded by the user:
let file = e.target.files[0];
// Create a file reader:
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
video.src = e.target.result;
}
}
However, when I uploaded really large video files (≈300 MB), e.target.result was not a URI to the video file, like I expected, but an empty string.
How can I read very large video files using File Reader in JavaScript?
The FileReader class in JavaScript contains multiple methods to read files:
readAsText(): This reads a file and returns its content as text. Suitable for small text files.
readAsBinaryString(): This reads a file and returns its content as a binary string. Suitable for small files of any type.
readAsDataURL(): This reads a file and returns a Data URL referencing it. This is inefficient for large files as the file is loaded into memory as a whole before being processed.
readAsArrayBuffer(): This reads a file and returns an ArrayBuffer containing the input file 'chopped up in smaller pieces'. This works for very large files, too.
In the question, the readAsDataURL() method is used as it is usually most convenient. However, for very large video files (and very large files in general) it does not work for the reason described above leading to an empty result. Instead, you should use readAsArrayBuffer():
let reader = new FileReader();
reader.readAsArrayBuffer(file);
Now, the file reader returns an ArrayBuffer after loading the file. In order to be able to show the video in HTML, we have to convert this buffer to a blob, that can then give us a URL to the video file:
reader.onload = function(e) {
// The file reader gives us an ArrayBuffer:
let buffer = e.target.result;
// We have to convert the buffer to a blob:
let videoBlob = new Blob([new Uint8Array(buffer)], { type: 'video/mp4' });
// The blob gives us a URL to the video file:
let url = window.URL.createObjectURL(videoBlob);
video.src = url;
}

Decoded Binary Audio from DataURL not writing properly to .mp3 file

I'm using the getUserMedia API to allow a user to record a short Audio clip on the client. After finishing the recording, I initialize a FileReader, create a Blob from all the Audio chunks, and read the reader of the blob as a DataURL. That gets appended as Text to a webform that's then sent to a Rails5 API, where I'm having a very difficult time converting the Binary Audio into a working .mp3 file.
Here is what the code looks like:
When the recorder goes inactive, the chunks are collected and used to instantiate a new Blob with the type 'audio/mpeg'.
var chunks = [];
if (recorder.state == 'inactive') {
var blob = new Blob(chunks, { type: 'audio/mpeg' });
App.mediaStream.encodeBase64(blob);
}
The Blob is then passed to a function that creates a base64 encoded DataURL.
encodeBase64: function(blob) {
var reader = new FileReader();
reader.onloadend = function() {
App.mediaStream.appendToForm(reader.result);
};
reader.readAsDataURL(blob);
},
The result from the reader is a dataURL that follows this pattern, data:[type];base64,[data] - so it's a String that looks like:
"data:audio/mpeg;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQRChYECGFOAZwH/////////FUmpZpkq17GDD0JATYCGQ2hyb21lV0GGQ2hyb21lFlSua7uuudeBAXPFh+bmBbc......."
I'm appending this DataURL to a form, that sends it to my Rails 5 API along with some other data. Here is where I'm running into trouble. On the server side, I have a ruby method that parses the dataURL, and writes it to a file as so:
def binary_to_audio_file(dataURL)
data = dataURL.split(',').last
filename = SecureRandom.hex
File.open("public/#{filename}.mp3", 'wb') do |f|
f.write Base64.decode64(data)
end
end
This is successfully creating a new file in the specified directory that has the decoded audio binary written to the file. That file can be opened by QuickTime, Itunes, or any other media play. It even plays for the same duration that the recording lasted. HOWEVER, there is NO sound.
I promise my speakers are not turned off... any hints?

How to convert a PDF file into a base64 string in java script

I have created an app in sencha touch cordova, and in my app I have a functionality to download PDFs.
I have successfully downloaded a pdf file, but now I want to convert the PDF into a base64 string using JavaScript.
Can anybody tell me how to do it?
See if your JavaScript environment has the "atob" and "btoa" functions available:
var encodedData = window.btoa("Hello, world"); // encode a string
var decodedData = window.atob(encodedData); // decode the string
These convert a string to and from Base64 encoding.
Trying using the logic below.
<input id="inputFile" type="file" onchange="convertToBase64();" />
function convertToBase64(){
//Read File
var selectedFile = document.getElementById("inputFile").files;
//Check File is not Empty
if (selectedFile.length > 0) {
// Select the very first file from list
var fileToLoad = selectedFile[0];
// FileReader function for read the file.
var fileReader = new FileReader();
var base64;
// Onload of file read the file content
fileReader.onload = function(fileLoadedEvent) {
base64 = fileLoadedEvent.target.result;
// Print data in console
console.log(base64);
};
// Convert data to base64
fileReader.readAsDataURL(fileToLoad);
}
}
Note : This snippet was taken from stackoverflow, but I dont remember the link :(

Decode base64 image and upload

I have a webapp that is saving images locally until they are ready to be sent to the server. When I save the images locally, I base64 encode them. Now I want to do a multipart file upload with these images.
So I need to convert the image back into binary form. I've tried using the FileReader to convert it back like this,
var fr = new FileReader();
fr.onloadend = function(binaryImage){
debugger;
binaryImage;
};
var base64Str = item.base64Image.substr(item.base64Image.indexOf("base64") + 7);
//var base64Str = item.base64Image;
fr.readAsBinaryString(base64Str);
but the onloadend event is never fired and there are no errors. Once I get the image I wont have trouble uploading it. Any ideas?
Thanks!
Not to familiar with FileReader, but I believe readAsBinaryString is expecting a Blob or File object. Passing it a string causes errors on my end. Try this:
var fr = new FileReader();
fr.onloadend = function(binaryImage){
debugger;
binaryImage;
};
var blob = new Blob([item.base64Image.
substr(item.base64Image.indexOf("base64") + 7)]);
fr.readAsBinaryString(blob);
I don't think this will give you want though. Check out this article for ways to encode/decode Base64: How can you encode to Base64 using Javascript?
Looks like you can use btoa() and atob() for web kit browsers.

Categories