Retrieve and save audio files on firebase

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:

  1. 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.
  2. 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.

Answer №1

If you're looking to store audio files, the Realtime Database may not be the best option for you. Consider using Firebase Storage instead. Check out Firebase Features for more information.

With Firebase Storage, you can easily store and retrieve user-generated content such as images, audio, and video directly from the client SDK.

Enjoy robust uploads and downloads in the background, regardless of network quality, secure client-side authorization integrated with Authentication, and petabyte-scale data storage backed by the Google Cloud Storage API. Access APIs throughout Firebase or Google Cloud Storage for seamless integration.

Answer №2

It appears that uploading the actual audio file is not possible.

After looking at some examples, I noticed that data (for image files) is uploaded in the form of a dataURL/Base64 string and then reconstructed after downloading.

Given that my audio files are small, around 60-70 kb, I have decided to follow a similar approach by using the same method to reconstruct the file with an HTMLAudio element.

Answer №3

If you're looking for a straightforward way to incorporate audio recording into your program, consider using the following two methods (referenced in the provided link).

private void initiateRecording() {
        mRecorder = new MediaRecorder();//mRecoreder has been declared globally
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(mFileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            mRecorder.prepare();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");//initiallize LOG_TAG as a string anything u like to get an indication
        }

        mRecorder.start();
    }

    private void haltRecording() {
        mRecorder.stop();
        mRecorder.release();
        mRecorder = null;

        uploadAudio();//it is'nt in the link. it has been added by me to upload ur audio to firebase storage cloud 

    }

To upload the code, simply call the method uploadAudio() with the following body:

private void uploadAudio() {

mProgressDialog.setMessage("Uploading Audio...");//declare it globally and initialize it with passing the current activity i.e this
mProgressDialog.show();

StorageReference mFilePath = mStorageRef.child("Audio").child("new_audio.3gp");

Uri u = Uri.fromFile(new File(mFileName));
mFilePath.putFile(u).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

        mProgressDialog.dismiss();
        mTextView.setText("Audio has been Uploaded Successfully !!!");
    }
});

}

This should suffice for simple audio uploading. For further customization options, refer to the link provided: https://developer.android.com/guide/topics/media/mediarecorder.html

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When an image is clicked, I am interested in loading HTML content

I am trying to implement a feature where a local HTML page can be loaded within a div to replace an existing one without the entire page having to reload. An example of what I want to achieve can be seen at . When you click on the game image, the player i ...

Intelligent search feature for table data with the ability to submit

Utilizing smart-table, I fetched a dataset from my API and implemented the st-search property to filter multiple parameters. However, I prefer not to update the table query every time the input is changed. I would rather use a submit button to reduce the ...

I am looking to include an SVG icon, like a separate React component, within the "title" parameter of a React-Bootstrap Drop Down

Looking to create a header with the Profile icon and Loggedin user positioned on the right side of the Bootstrap Navbar. My goal is to achieve a UI similar to the image linked below without using the Dropdown component. In the image, there are two parts ...

Concentrate and select non-interactive elements with your mouse

Is it possible to set tab index on non-form elements like the div tag? I tried using tab index, but when the div is focused and the enter button is tapped, the ng-click event associated with the div tag is not triggered. <div tabindex="0" role="butto ...

Dealing with errors when chaining promises in a react-redux application

This is related to a question asked on Stack Overflow about Handling async errors in a react redux application In my react-redux setup, I am facing a scenario where I need to chain multiple API calls upon successful completion of each. How can I achieve ...

Transferring information between a service and a controller

I'm struggling to pass data between a service and a controller in my AngularJS project. Even though I've followed the recommended steps, the code is not functioning as expected. Below is the controller snippet: function udpController($scope ...

Modify the standard localStorage format

I'm encountering a dilemma with my two applications, located at mysite.com/app1 and mysite.com/app2. Both of these apps utilize similar localStorage keys, which are stored directly under the domain "mysite.com" in browsers. This setup results in the l ...

Manipulating JSON Objects in AngularJS

While I may be proficient in utilizing existing data, my expertise in editing JSON objects is not quite up to par yet. Any assistance in this area would be greatly appreciated. This question may seem basic, but I am seeking clarification as I am unsure. H ...

Is there a way to sort data by year and month in mongodb?

I'm trying to filter data by year in MongoDB based on a specific year and month. For example, if I pass in the year 2022, I only want to see data from that year. However, when I try using the $gte and $lte tags, it returns empty results. Can someone g ...

The function of edit does not exist

I'm currently working on creating a discord bot that will send a message to a specific channel upon startup. Initially, I was able to send the message to the designated channel without any issues. However, when I attempted to edit the message, an erro ...

Is the inclusion of 'useClient' in the root layout of Next.js 13 responsible for converting all routes into client components?

Recently, I delved into experimenting with Nextjs 13 alongside Next-auth and Apollo Client. To make this setup work, we wrapped the root layout with all the necessary providers, including specifying 'use client'. Fortunately, I didn't encoun ...

Sending information through AJAX in Elgg

Is there a way to transfer information between two PHP files using AJAX with Elgg? data_from_here.php <?php $entity = elgg_extract('entity', $vars, FALSE); $guid = $entity -> guid; require_js('javascript_file.js'); ...

Updating the ContextKey of the DynamicPopulateExtender based on the selected value from a DropDownList dynamically

I am facing an issue with my DynamicPopulateExtender control. I need it to render HTML based on the value of an asp:DropDownList. The problem lies in writing the JavaScript code that can fetch the dropdown value, assign it to the DynamicPopulate control&ap ...

How to disable click event binding in Angular2 after it has been clicked once

Within my application, there is a button that has a click event attached to it: <button class="btn btn-default" (click)="doSomething()"> I am wondering if there is a way to remove the (click) event from the button within the doSomething method so t ...

Navigating Error: net::ERR_CONNECTION while utilizing Puppeteer

I attempted to utilize a proxy from the following site: Below is my Puppeteer scraping code (deployed on Heroku), encountering an error at the .goto() method, as mentioned in the title: const preparePageForTests = async (page) => { const userAgent = & ...

Update the router on component.ts

Is there a way to reload my page route to refresh the data stored in it by using a function in the Typescript file instead of adding routerLink directly in the html? I have come across location.reload and location.href but they refresh the entire page. Fu ...

Leveraging Express.js alongside websockets

I am currently working on an application that is built on Expressjs and Angularjs. I am looking to incorporate a few two-way calls in addition to the existing HTTP calls. While I have gone through some websocket chat tutorials, none of them seem to be inte ...

Discovering the method to validate every individual letter entered against a specific keyword

I am in the process of developing a game where users have to input each letter of a hidden word and receive feedback on whether their guess is correct or not. You can view the current version of the game at: . While the game functions as intended, there i ...

Is it possible to utilize $(this) within the $.post() function?

I seem to be having trouble accessing $(this) from inside the $.post section. It works perfectly fine outside of it. Here is the JavaScript code: $('.idea').each(function(){ var title = $(this).html(); $.post("votes.php", { t ...

Troubleshooting the error message "XMLHttpRequest cannot load" when using AngularJS and WebApi

I have developed an asp.net webApi and successfully published it on somee.com. When I access the link xxxx.somee.com/api/xxxx, everything works fine. However, when I try to call it in Angularjs, it does not work. $http.get('http://xxxxxx.somee.com/ap ...