How to load base64 audio locally on cordova mobile? - javascript

I've been trying to load an audio file already encoded in base64 but to no avail. I can load encoded images easily, but I can't do it with audio. The example I found with cordova audio is passing url link to the asset folder, but I tried that and it didn't work.
Is there a way to play an audio file encoded in base64 directly?

I tried cordova-plugin-media but it seems to work only with files and not with base64 code.
Finally I found this solutions:
SOLUTION 1:
var src = "data:audio/mp3;base64," + your_base64_code;
document.write("<audio preload='auto' autoplay><source src='" + src + "' /></audio>");
SOLUTION 2:
1) Convert the base64 code to an audio files, saving it in the cache folder.
You can read this article to do it: How to create an audio file from a mp3 base64 string on the device with Cordova
You can use as target folder: cordova.file.cacheDirectory
For example:
saveBase64AsAudioFile(cordova.file.cacheDirectory, "audiofile.mp3", your_base64_code, "audio/mp3");
2) Use the cordova-plugin-media to play the created file:
setTimeout(function () {
var src = cordova.file.cacheDirectory + "audiofile.mp3";
var media = new Media(src);
media.play();
}, 2000);
Use setTimeout to be sure that the files is already created.

Related

How to play sound in javascript without external audio file/html file?

So im building something but im not allowed to use any external files other than the script.js file itself. I want to play a .mp3 sound in a function but im not sure how to do it without uploading the file into my folder.
You can use javascript to set the audio data src to data:audio/ogg;base64,T2dnUwACAAAAAAAAAAA+... etc.
There's an example here. https://iandevlin.com/html5/data-uri/audio.php
To do this with javascript simply
var audioElement = new Audio();
audioElement.src = "data:audio/ogg;base64,T2dnUwACAAAAAAAAAAA+...";
audioElement.play();
You can encode your mp3 file using base64. Than you can the audio in a string:
var beep = "data:audio/mp3;base64,<paste your base64 here>";
var audio = document.getElementById('audio');
audio.src = beep;
audio.play();
The base64 string can be generate using a shell
cat sound.mp3 | base64

Using window.URL.createObject in chrome intermittently failing when downloading multiple files

The crux of the question: I am consecutively downloading 2 files in javascript and chrome will intermittently switch between downloading one file or both. The setting to download multiple files automatically is activated.
The details:
For an internal app I am maintaining, there is a routine that retrieves two sets of base64 strings from an API. This app is only run in the latest version of google chrome but on both windows 8, 10 and the latest version of OSX.
The front end then decodes these strings into a data blob and then decodes the blobs into 2 csv's and downloads them.
The Web API I am using to download the files is the createObjectURL(), assuming the base64 is decoded correctly into a blob (which it is as this is used in multiple other instances) the function to download a file is as follows:
function downloadBlob (blob, filename, extension) {
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = filename + '.' + extension;
// Append anchor to body.
document.body.appendChild(a);
a.click();
// Remove anchor from body
document.body.removeChild(a);
}
Again this is used in multiple instances and has worked without a hitch.
So an AJAX request is made to the API to retrieve the two base64 strings, the success callback is essentially:
Function success (b64A, b64B) {
var csvA = b64toBlob(b64A, 'application/vnd.ms-excel');
downloadBlob(csvA, 'filename', 'csv');
var csvB = b64toBlob(b64B, 'application/vnd.ms-excel');
downloadBlob(csvB, 'filename', 'csv');
}
As you can see the downloads are executed consecutively. This has been tested across both chrome in windows 8 and chrome on OSX and both seem to intermittently download both files. Most of the time they only download the latter file.
I'm a bit confused as to why this was happening and was wondering if this is an issue with my code or some niche glitchy behaviour in chrome.
I was using HTML code and jquery to download multiple files but a few days ago i can download just the latest file.
I think now is blocked by Chrome.
I'm not sure if this is a bug in Chrome or intended behaviour however I managed to solve this by wrapping the second downloadBlob() in a setTimeout of 200ms:
Function success (b64A, b64B) {
var csvA = b64toBlob(b64A, 'application/vnd.ms-excel');
downloadBlob(csvA, 'filename', 'csv');
setTimeout(function() {
var csvB = b64toBlob(b64B, 'application/vnd.ms-excel');
downloadBlob(csvB, 'filename', 'csv');
}, 200);
}

blob garbage collection issue

I'm attempting to use the html5 file input functions by kartik# to upload a large amount of images. I would prefer that the end user didn't have to resize images prior to uploading so I am using the resizeImage option#. I run into issues when uploading large files (3-4MB each).
I have modified fileinput.js to replace the preview image with the resized blob, however my browser (Chrome 48.0.2564.103 m) still lists the original (large filesize) blob in the F12 -> Resources -> ... -> Images folder. When uploading hundreds of images, the browser will eventually run out of memory and crash.
I can't find any reference to the original/large blob in the 'self' object of fileinput.js so I'm at a loss as to how to have this unused blob garbage collected.
jsfiddle of issue / link to modified fileinput.js (modifications made :2396-2412)
setTimeout(function(d) {
console.log('attempting to replace original blob with:');
console.log(blob);
console.log(objUrl.createObjectURL(blob));
console.log('attempting to revoke original blob: ' + image.src);
objUrl.revokeObjectURL(image.src);
delete image.src;
self.clearDefaultPreview();
image.src = objUrl.createObjectURL(blob);
console.log('outputting fileinput.js self var:');
console.dir(JSON.stringify(self));
console.dir(self);
}, 500);
}, type, self.resizeQuality);
console.log('current image.src blob is: ' + image.src);
#I don't have the reputation to post more than two links, so I have embedded links to the plugin documentation within the javascript frame on jsfiddle.
Any help would be greatly appreciated.
I figured out what was going on, the fileinput script wasn't resizing the blobs until after all images had been preloaded. After modifying it to process each image one at a time, my performance was working as well as could be expected with such large images - Thank you guys for your comments.

How to save an Image object into a file in Android with Phonegap?

Here's the thing, I generate a PNG image in the application and I get an Image object with JavaScript, something like this...
var img = new Image();
img.src = 'data:image/png;base64,' + base64Img;
I want to save that image to the internal storage. Is there a plugin or a way I can do this?
According THIS QUESTION:
This is file download code which can be used by anyone. You just have three parameters to use this like-
1) URL
2) Folder name which you want to create in your Sdcard
3) File name (You can give any name to file)
All types of file can download by using this code. you can use this as .js
And this works on IOS also.
First step check parameters mismatch and checking network connection if available call download function
Second step to get Write permission and Folder Creation
Third step for download a file into created folder
Also check this link
function onPhotoDataSuccess1(imageData) {
alert(imageData);
sessionStorage.setItem("img_api",imageData);
$('#largeImage').attr('src','data:image/jpeg;base64,' + imageData);
}
Hope, it will helps you!

JavaScript FileReader using a lot of memory

I have a problem with my little project.
Every time the music player is loading new songs into playlist or you are pressing a song on the list to get it playing, it's using a lot of memory, and it stays high until you shut it down. I think its every time I'm using the filereader API that it uses memory, but I'm also loading ID3 information with the jDataView.js script which I also think is taking a lot of memory.
Do you guys have any suggestion, to load,store and play songs with the FileReader, without taking up memory? I've tried to see if it was possible to clear the fileReader after using, but I couldn't find anything. I've only tested in Chrome.
UPDATE:
I have tested my project,and found out, that its when im trying to load the datastring it takes up memory.
reader.onloadend = function(evt) {
if(typeof(e) != "undefined"){
e.pause();
}
e = new Audio();
e.src = evt.target.result; // evt.target.result call takes the memory
e.setAttribute("type", songs[index]["file"].type);
e.play();
e.addEventListener("ended", function() { LoadAudioFile(index + 1) }, false);
};
Is there another way to load the data into the audio element?
This is not because of FileReader but because you are making the src attribute of audio element a 1.33 * mp3filesize string. So instead of the src attribute being a nice short url pointing to a mp3 resource, it's the whole mp3 file in base64 encoding. It's a wonder your browser didn't crash.
You should not read the file with FileReader at all, but create a blob URL from the file and use that as src.
var url = window.URL || window.webkitURL;
//Src will be like "blob:http%3A//stackoverflow.com/d13eb575-4863-4f86-8727-6400119f4afc"
//A very short string that is pointing to the original resource in hard drive
var src = url.createObjectURL( mp3filereference );
audioElement.src = src;

Categories

Resources