I am currently facing a challenge in my attempt to upload an audio file and then download it later. My approach involves utilizing the Firebase server for this process.
There are two specific queries that I find myself stuck on. Resolving either of them would help me achieve my goal:
- Is there a way to upload the file as a file directly, without converting it to a blob first? Currently, I convert the file to a blob before uploading it, but I believe there must be a more efficient method available.
- While I can successfully download the file, I encounter difficulties when attempting to play it back. Since the file is initially converted to DataURL/ArrayBuffer before being uploaded, how can I convert it back to an audio format like mp3 or wav?
Below is the code snippet used for uploading the file:
$scope.uploadFile = function(){ // uploading file
var storageRef= firebase.storage().ref();
var filename= $scope.audio.src.substring($scope.audio.src.lastIndexOf("/")+1,$scope.audio.src.length);
$scope.fname= filename;
// fetching file to upload
baseServ.dirEntry.getFile(filename, {}, function(entry){
entry.file(function(gotfile){
var reader= new FileReader();
reader.onloadend= function(resultFile){
console.log(resultFile);
var blob= new Blob([resultFile], {type:"audio/mp3"});
// uploading to firebase server
var uploadTask = storageRef.child(filename).put(blob);
uploadTask.on('state_changed', function(snapshot){
console.log("state_changed:" + filename + "::::Current State:" +snapshot.state);
}, function(error) {
alert("upload error");
}, function() {
$scope.downloadURL = uploadTask.snapshot.downloadURL;
});
}
//reading as dataUrl or ArrayBuffer
reader.readAsDataURL(gotfile);
})
});
}
And here is the code section responsible for downloading the file:
$scope.downloadFile= function(){
var ft= new FileTransfer();
ft.download($scope.downloadURL, baseServ.dirDownloads.nativeURL + $scope.fname, function(entry) {
// download is successful but unable to play when opening in my device
console.log("download complete: " + entry.toURL());
},
function(error) {
console.log("download error source " + error.source);
},
false,
{});
}
I appreciate any assistance with resolving these challenges. Thank you.