Search code examples
angularjscordovafirebaseionic2firebase-storage

How to upload audio file to Firebase Storage?


I'm trying to upload audio file to Firebase Storage in my Ionic2 project.

First I recorded a audio file using Media plugin (Cordova plugin), and this file is playing well. From the Android storage and from the media plugin method (this.media.play()...;).

Second I need to push the recorded file to Firebase Storage.

this is my code:

  let storageRef = firebase.storage().ref();
  let metadata = {
     contentType: 'audio/mp3',
   };
  let filePath = `${this.file.externalDataDirectory}`+`${this.fileName}`;
  const voiceRef = storageRef.child(`voices/${this.fileName}`);  
  var blob = new Blob([filePath], {type: 'audio/mp3'});
  voiceRef.put(blob);

After reading the Firebase doc, I can push blob to Firebase.

The file is successfully pushed to Firebase Storage with empty data (95 Byte).

this is screenshot:enter image description here


Solution

  • The problem isn't a Firebase issue

    My problem is solved by using the File cordova plugin method (readAsDataURL()) and the putString(fileBase64,firebase.storage.StringFormat.DATA_URL) method.

    First, I create a file reference: let filePath = "this.file.externalDataDirectory" + "this.fileName";

    Then I transform the file to a base64 string by using the readAsDataURL method that returns a promise containing the file as a string base64. Also, I push the file to Firebase using the putString method that has two parameters the File that returned by the readAsDataURL and the second is firebase.storage.StringFormat.DATA_URL.

    My Final code:

      let storageRef = firebase.storage().ref();
      let metadata = {
        contentType: 'audio/mp3',
      };
      let filePath = `${this.file.externalDataDirectory}` + `${this.fileName}`;
      this.file.readAsDataURL(this.file.externalDataDirectory, this.fileName).then((file) => {
        let voiceRef = storageRef.child(`voices/${this.fileName}`).putString(file, firebase.storage.StringFormat.DATA_URL);
        voiceRef.on(firebase.storage.TaskEvent.STATE_CHANGED, (snapshot) => {
          console.log("uploading");
        }, (e) => {
          reject(e);
          console.log(JSON.stringify(e, null, 2));
        }, () => {
          var downloadURL = voiceRef.snapshot.downloadURL;
          resolve(downloadURL);
        });
      });
    

    That's working fine for me. Thanks.