How to Convert Uploaded Audio to Blob using Javascript? - javascript

I am trying to capture the audio that's uploaded by the user, convert it to Blob then using wavesurfer.js to display the waveform.
I am following this instruction here https://bl.ocks.org/nolanlawson/62e747cea7af01542479
And here is the code
// Convert audio to Blob
$('#audioFileInput').on('change', function () {
var file = $('#audioFileInput')[0].files[0];
var fileName = file.name;
var fileType = file.type;
var fileReader = new FileReader();
fileReader.onloadend = function (e) {
var arrayBuffer = e.target.result;
blobUtil.arrayBufferToBlob(arrayBuffer, fileType).then(function (blob) {
console.log('here is a blob', blob);
console.log('its size is', blob.size);
console.log('its type is', blob.type);
surfTheBlob(blob);
}).catch(console.log.bind(console));
};
fileReader.readAsArrayBuffer(file);
});
But it says
blobUtil.arrayBufferToBlob(...).then is not a function
Another issue is that since the user might upload the audio themselves, the audio type might vary, expected to come from native device audio recorder. Anyone can help please? thanks.

A File object, like the ones you get in the input.files FileList, is already a Blob:
inp.onchange = e =>
console.log(inp.files[0] instanceof Blob) // true
<input type="file" id="inp">
So all you really need is to pass directly this File to your library:
$('#audioFileInput').on('change', function () {
var file = this.files[0];
surfTheBlob(file);
});

Found the answer already.
// Convert audio to Blob
$('#audioFileInput').on('change', function () {
var file = $('#audioFileInput')[0].files[0];
var fileName = file.name;
var fileType = file.type;
var url = URL.createObjectURL(file);
fetch(url).then(function(response) {
if(response.ok) {
return response.blob();
}
throw new Error('Network response was not ok.');
}).then(function(blob) {
surfTheBlob(blob);
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
});
Cheers!

Related

How would I convert an image to base64 in reactJS

I have this function where I call a function and have a local file as the parameter to convert it to base64.
export const fileToBase64 = (filename, filepath) => {
return new Promise(resolve => {
var file = new File([filename], filepath);
var reader = new FileReader();
// Read file content on file loaded event
reader.onload = function(event) {
resolve(event.target.result);
};
// Convert data to base64
reader.readAsDataURL(file);
});
}
Importing the function
fileToBase64("shield.png", "./form").then(result => {
console.log(result);
console.log("here");
});
gives me an output as
data:application/octet-stream;base64,c2hpZWxkLnBuZw==
here
I want base64 information, but noticing the file the application/octet-stream is wrong? I entered an image so shouldn't it be
data:image/pgn;base64,c2hpZWxkLnBuZw==
https://medium.com/#simmibadhan/converting-file-to-base64-on-javascript-client-side-b2dfdfed75f6
try this I think this should helpfull
let buff = new Buffer(result, 'base64');
let text = buff.toString('ascii');
console.log(text)

file reader read blob file

i am trying to use filereader to access a blob file located locally, such as c drive, then converts it back to object URL as img src. it is not working, can anyone help this?
never found anyone try to access a blob file from disk. what is the blob file type extension?
const imageOut = document.querySelector('#image-out');
imageOut.addEventListener('load', () => {
const reader = new FileReader();
reader.addEventListener('load', () => {
var f = File.createFromFileName("file:///C:/blob.blb");
const arrayBuffer = reader.readAsArrayBuffer(f);
const blob = new Blob([arrayBuffer], { type: mimeType });
imageOut.src = URL.createObjectURL(blob);
});
});
empty, not show
Check how to use blob here it is clearly explained and it should be enough to get you going.
Try this:
Assuming that file:///C:/blob.blb exists and you are sure, then do it like so:
imageOut.addEventListener('load', () => {
const reader = new FileReader();
var f = File.createFromFileName("file:///C:/blob.blb");
reader.addEventListener('load', (e) => {
const arrayBuffer = reader.readAsArrayBuffer(f);
global.blob = new Blob([arrayBuffer], { type: f.type});
});
// notice this is outside the reader Load.
var intval = setInterval(function(){
if(blob !== undefined){
imageOut.src = URL.createObjectURL(blob);
clearInterval(intval);
}
}, 100);
});
I hope it helps.

View blob response as image in angular

I am trying to get a blob response from a request, and then generate a URL from that blob and set this URL as an image's source.
But the image is not loading.
This is my HTML:
<img src="{{previewSignsrc}}" alt="Sign Thumbnail">
And this is my .ts file:
this.signModalDataService.getPreviewSignature({'name': this.SignatureName, 'font_type': 0});
this.signModalDataService.previewSignature
.subscribe((res) => {
console.log(res);
let blob = new Blob([res['_body']], {type: 'image/png'});
this.previewSignsrc = URL.createObjectURL(blob);
this.showPreviewSign = true;
});
I used same method to set url for ng2-pdfviewer and it worked fine.
You can dislay image like this code
this.config.getData()
.subscribe((blob : any) => {
let objectURL = URL.createObjectURL(blob);
this.image = this.sanitizer.bypassSecurityTrustUrl(objectURL);
});
If your data is base64 display like this
this.config.getData()
.subscribe((baseImage : any) => {
let objectURL = 'data:image/jpeg;base64,' + baseImage.image;
this.thumbnail = this.sanitizer.bypassSecurityTrustUrl(objectURL);
});
Demo https://stackblitz.com/edit/display-image-from-api
As was metioned earlier by Memo 313 MediaSA, FileReader works.
const reader = new FileReader();
reader.readAsDataURL(data); //FileStream response from .NET core backend
reader.onload = _event => {
url = reader.result; //url declared earlier
image.nativeElement.src = url; //image declared earlier
};
You can use new FileReader(); I tried so much codes and that's the only one that worked for me.
var reader = new FileReader ();
reader.readAsDataURL(response) <= from inner . subscribe
reader.onload = (_event) => {
this.retrieveURL = reader.result;
}
.html
[src]="retrieve URL"
Bear with me I typed from my cellphone
That's all no need to use sanitizers, hope it helps somebody out there, ooh I am using Angular8
this code is the best for blob(for example asp file stream in backend) and 100% work.
.ts:
image: any;
constructor(
private sanitizer: DomSanitizer,
) { }
this.signModalDataService.previewSignature
.subscribe(blob => {
let objectURL = URL.createObjectURL(blob);
this.image = this.sanitizer.bypassSecurityTrustUrl(objectURL);
})
.html
<img [src]="image">
If you use JsonConvert from a .Net API to return an object in which one of the fields is the image byte[] it will convert it to a base64 string. Then you don't need anything special when calling the api or displaying the image.
This works for me:
this.httpClient.get(Endpoints.PRODUCTS + '/pictures/download', {'params': queryParams, responseType: 'blob'})
.subscribe(
value => {
// Add Preview
const reader = new FileReader();
reader.readAsBinaryString(value);
const addPreview = (fileBase64) => {
this.urls.push(`data:${value.type};base64,${btoa(fileBase64)}`);
};
reader.onload = function (e) {
addPreview(e.target.result);
};
},
(error) => {
// Refactor
// this.errorList = error.error.data.errorList;
console.log(error);
})
;

Get base64 of audio data from Cordova Capture

I am using ngCordova Capture to write this code by recording audio and send the base64 somewhere (via REST). I could get the Capture Audio to work but once it returns the audioURI, I cannot get the data from the filesystem as base64. My code is below:
$cordovaCapture.captureAudio(options).then(function(audioURI) {
$scope.post.tracId = $scope.tracId;
$scope.post.type = 'audio';
console.log('audioURI:');
console.log(audioURI);
var path = audioURI[0].localURL;
console.log('path:');
console.log(path);
window.resolveLocalFileSystemURL(path, function(fileObj) {
var reader = new FileReader();
console.log('fileObj:');
console.log(fileObj);
reader.onloadend = function (event) {
console.log('reader.result:');
console.log(reader.result);
console.log('event.result:');
console.log(event.result);
}
reader.onload = function(event2) {
console.log('event2.result:');
console.log(event2.target.result);
};
reader.readAsDataURL(fileObj);
console.log(fileObj.filesystem.root.nativeURL + ' ' + fileObj.name);
$cordovaFile.readAsDataURL(fileObj.filesystem.root.nativeURL, fileObj.name)
.then(function (success) {
console.log('success:');
console.log(success);
}, function (error) {
// error
});
});
Here is the output in console log:
So how do I get the base64 data from the .wav file?
I have been reading these links:
PhoneGap FileReader/readAsDataURL Not Triggering Callbacks
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
http://jsfiddle.net/eliseosoto/JHQnk/
http://community.phonegap.com/nitobi/topics/filereader_onload_not_working_with_phonegap_build_2_5_0
Had same problem, which I fixed using both the Cordova Capture and Cordova File plugin.
navigator.device.capture.captureAudio(function (audioFiles) {
var audioFile = audioFiles[0],
fileReader = new FileReader(),
file;
fileReader.onload = function (readerEvt) {
var base64 = readerEvt.target.result;
};
//fileReader.reasAsDataURL(audioFile); //This will result in your problem.
file = new window.File(audioFile.name, audioFile.localURL,
audioFile.type, audioFile.lastModifiedDate, audioFile.size);
fileReader.readAsDataURL(file); //This will result in the solution.
});

blob not storing any value for any reason

Recording a video with webRTC I have no data, and after debugging I just realized that there's no content in the Blob variable (that must store the video).
According to the code I pasted on my jsfiddle, line 136 should contain something like:
Blob {type: "audio/wav", size: 360492, slice: function}size: 360492type: "audio/wav"
But its value is undefined.
Could anybody tell me what am I doing wrongly?
You have to call stopRecording and get the blob within the callback. The callback will also be passed a data URL.
if (!isFirefox) {
recordAudio.stopRecording(function(dataURL){
var bloba = recordAudio.getBlob();
console.log("Audio Blob",bloba);
});
fileType = 'audio';
fileName = 'test.wav';
} else {
recordAudio.stopRecording(function(dataURL){
var bloba = recordAudio.getBlob();
console.log("Audio Blob",bloba);
});
fileType = 'video';
fileName = 'test.webm';
}
if (!isFirefox) {
recordVideo.stopRecording(function(dataURL){
var blobv = recordVideo.getBlob();
console.log("Video Blob",blobv);
});
fileType = 'video';
fileName = 'test.webm';
}
Updated Fiddle

Categories

Resources