I want to load an audio file via input file reader and then be able to play it ...
Here is the process of creating file blob and assign the audio source to this blob:
fileInput.on('change', readFile);
function readFile(e) {
const input = e.target;
if(input.files && input.files[0]) {
const reader = new FileReader();
reader.onload = (e) => {
const binaryData = e.target.result;
const binary = convertDataURIToBinary(binaryData);
const blob = new Blob(binary, {type: input.files[0].type });
console.log('inserting blobXX', blob);
recordedAudioComponent.src = URL.createObjectURL(blob);
data.instructAudios[component] = blob;
console.log('recordedAudioComponent.src', recordedAudioComponent.src);
}
reader.readAsDataURL(input.files[0]);
}
}
And here is the result of above code on console:
Now I'm trying to play the recordedAudioComponent which is an audio tag with the source right?
const recordedAudioComponent = document.getElementById(`recordedAudio-instruct-${component}`);
console.log(recordedAudioComponent)
recordedAudioComponent.play();
And here is the error it produces:
How can I fix this and play the audio?
EDIT: Here is the function to get the blob in the first code:
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
You don't need any of convertion, blob is actually pretty similar from the file itself and the method URL.createObjectURL accepts file as argument, all you need to do to play the audio file from your browser is set the src attribute as the url created, something like this:
<body>
<input style="display: block;" type="file" onchange="loadAudioFile(this)">
<audio src=" " id="track" controls>
</audio>
<script>
function loadAudioFile(e) {
const url = URL.createObjectURL(e.files[0]);
document.getElementById('track').setAttribute('src', url);
}
</script>
</body>
<input type="file" name="fileInput" id="fileInput">
<script>
const fileInput = document.querySelector('#fileInput');
fileInput.onchange = readFile;
/** #type {AudioNode} */
const audio = document.createElement( 'audio' );
function readFile(e) {
const input = e.target;
if(input.files && input.files[0]) {
const reader = new FileReader();
reader.onloadend = function (e){
audio.src = e.target.result;
audio.play();
}
reader.readAsDataURL(input.files[0]);
}
}
</body>
Related
Here is my text field
<input type="file" name="noteMedia[]" multiple id="ssi-upload" />
Variables
const dT = new DataTransfer();
const fileInput = document.getElementById("ssi-upload");
I'm adding copy and paste feature, so i do this
document.onpaste = function(event){
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
const dTLocal = new DataTransfer();
for (index in items) {
var item = items[index];
if (item.kind === 'file') {
var blob = item.getAsFile();
var reader = new FileReader();
dTLocal.items.add(blob);
fileInput.files = dTLocal.files;
reader.readAsDataURL(blob);
}
}
$("#ssi-upload").change();
i=i+1
}
and here is my #ssi-upload.change()
$("#ssi-upload").change(function(){
$("#imagePreview").html("");
var file = $(this)[0].files[0];
dT.items.add(file);
fileInput.files = dT.files;
imageIndex = 0;
Array.from(dT.items).forEach(item => {
var blob = item.getAsFile();
var image = new Image()
var reader = new FileReader();
var uri = URL.createObjectURL(blob);
var img = new Image();
img.src = uri;
var imagePreview = "<img width = '150px' height='100px' src='"+uri+"'>";
$("#imagePreview").append('<td style="text-align:center; vertical-align:middle">'+imagePreview+'<p class="text-center" align="text-center"> <a onclick="return deleteImage('+imageIndex+');" href="#"> Delete </a></p> </td>');
imageIndex = imageIndex + 1
});
});
So i want to have two ways to adding file, copy paste and default way from the input field. So, the problem is when i'm trying to delete the item deleteImage
function deleteImage(index){
const fileListArr = Array.from(fileInput.files)
fileListArr.splice(index, 1)
$("#ssi-upload").change()
}
The result is instead of remove file it is adding another file. So, how can i fix it ?
JSFiddle
Remove $("#ssi-upload").change() and add class to td like img-preview and pass this params to deleteImage so you can access that element. check the snippet below.
const dT = new DataTransfer();
const fileInput = document.getElementById("ssi-upload");
var i = 0;
let imageIndex = 0;
document.onpaste = function(event){
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
const dTLocal = new DataTransfer();
for (index in items) {
var item = items[index];
if (item.kind === 'file') {
var blob = item.getAsFile();
var reader = new FileReader();
dTLocal.items.add(blob);
fileInput.files = dTLocal.files;
reader.readAsDataURL(blob);
}
}
$("#ssi-upload").change();
i=i+1
}
$("#ssi-upload").change(function(){
$("#imagePreview").html("");
var file = $(this)[0].files[0];
dT.items.add(file);
fileInput.files = dT.files;
imageIndex = 0;
Array.from(dT.items).forEach(item => {
var blob = item.getAsFile();
var image = new Image()
var reader = new FileReader();
var uri = URL.createObjectURL(blob);
var img = new Image();
img.src = uri;
var imagePreview = "<img width = '150px' height='100px' src='"+uri+"'>";
$("#imagePreview").append('<td class="img-preview" style="text-align:center; vertical-align:middle">'+imagePreview+'<p class="text-center" align="text-center"> <a onclick="return deleteImage('+imageIndex+',this);" href="#"> Delete </a></p> </td>');
imageIndex = imageIndex + 1
});
});
function deleteImage(index,obj){
const fileListArr = Array.from(fileInput.files)
fileListArr.splice(index, 1);
console.log(fileListArr);
$(obj).closest('.img-preview').remove();
//$("#ssi-upload").change()
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="noteMedia[]" multiple id="ssi-upload" />
<table class="table" id="imagePreview"><tbody></tbody></table>
I have <input type="file" name="Video" id="videoSelect" accept="video/mp4" class="FileUpload" /> in my HTML and I want to save the file selected on my server. I already have
var videoID = uuidv4();
var VideoFile = videoSelector.files[0];
var reader = new FileReader();
reader.readAsDataURL(VideoFile);
var senddata = new Object();
senddata.name = videoID;
senddata.size = VideoFile.size;
senddata.type = VideoFile.type;
reader.addEventListener(
"load",
function () {
vidprv.src = reader.result;
vidprv.style.display = "block";
senddata.fileData = reader.result;
},
false
);
in my JavaScript file. I don't know how to save it to the server now
I have to upload in IE8 in enterprise mode.
In IE9 or higher I can do like
<input type="file" accept="jpg" id="inputer" onchange="uploadImage(event)">
function uploadImage (event){
var fileList = event.target.files;
console.log(fileList);
}
but how do that in IE8, because in IE8 event.target == undefined?
It was researched here
I have to upload that files into server
We did some function like
var FileReader = (function () {
function YourOwnEncoderStringTOArray(str){//your code}
function FileReader(){
var reader = new ActiveXObject("Scripting.FileSystemObject");
this.getFileSize = function(filename){
var file = reader.getFile(filename);
return file && file.size;
};
this.getBytes = function (filename){
var file = reader.getFile(filename);
var size = file.size;
var stream = file.OpernAsTextStream(1,0);
var str = stream.Read(size);
stream.Close();
return YourOwnEncoderStringTOArray(str);
};
}
return FileReader;
})();
And you can call it from your js like
window.YourFunc = function(event){
var filename = $('myElementId').val();
var fileReader = new FileReader();
var fileSize;
try{
fileSize = fileReader.getFileSize(filename);
}catch(e){
// your code to explain why fileReader do not answer
}
}
MediaRecorder ondataavailable work successful once.
I need to get blob, get it base64, send to my server, decode this base64 to audio blob.
This is very strange.
For example, output:
blob1
blob2
blob3
blob4
blob5
blob6
blob7
blob8
blob9
....
I can hear just blob1, other blobs is "disabled".
Try it!
This code record audio:
window.startRecord = function(cb){
var int;
navigator.mediaDevices.getUserMedia({ audio: true , video:false}).then(function(stream){
var options = {
audioBitsPerSecond : 128000,
videoBitsPerSecond : 2500000,
mimeType : 'audio/webm\;codecs=opus'
}
if(!MediaRecorder.isTypeSupported(options['mimeType'])) options['mimeType'] = "audio/ogg; codecs=opus";
window.voice = new MediaRecorder(stream, options);
voice.start(500);
voice.ondataavailable = function(data){
var reader = new FileReader();
var blob = data.data;
reader.readAsDataURL(blob);
reader.onloadend = function () {
var result = reader.result;
cb(result);
}
};
voice.onstop = function(){
console.log('stop audio call');
}
});
}
window.convertDataURIToBinary = function(dataURI) {
var BASE64_MARKER = ';base64,';
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
<body>
<button onclick="startRecord(function(r){
var binary= convertDataURIToBinary(r);
var blob=new window.Blob([binary], {type : 'audio/webm'});
var blobUrl = window.URL.createObjectURL(blob);
console.log('URL : ' + blobUrl);
document.getElementById('data').append(blobUrl + `
|
`);
})">Exec</button>
<div id="data">
</div>
<body>
</body>
I am not sure what is the problem you try to highlight, but:
The dataavailable event's data property contains only a chunk of the whole data that has been recorded.
For instance, only the first chunk will contain the metadata needed for the final recorded media.
It is then expected that you will merge all these chunks together at the time you will export them.
And this should be done only once, at the MediaRecorder.stop event.
const chunks = []; // store all the chunks in an array
recorder.ondataavailable = e => chunks.push(e.data);
// merge the chunks in a single Blob here
recoder.onstop = e => export_media(new Blob(chunks));
In JQuery, How can i get image element from url?
For example,
<input type="file" id="fileInput"/>
var fileInput = document.getElementById('fileInput');
Here its is done via file picker in html5. But, how could i get image from just url?
My requirement is to get image from url.
var fileInput = document.getElementById('fileInput'); //instead of this how could i get element from url
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
//save to file api
} else {
fileDisplayArea.innerHTML = "File not supported!";
}
});
Please help,
Thanks
Do like that:
var fileInput = document.getElementById('fileInput'); //instead of this how could i get element from url
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = (function(file){
return function(e){
// do something
}
})(file)
reader.readAsDataURL(file):
} else {
fileDisplayArea.innerHTML = "File not supported!";
}
});
Reading files in JavaScript using the File APIs