Ionic 3 get base64 audio string from recorded file

2019-03-06 04:48发布

问题:

I am using cordova-plugin-media to record voice(with pause and resume features) in my ionic app for android. After I record it I need to get base64 string in order to play it using html audio tag. And the problem is: if I am trying to save recording which was paused and resumed as 3gp file('voice.3gp'), then when I use readAsDataURL method of cordova-plugin-file, I don't receive anything(the callback simply not called). If I am trying to save it as mp3 or wav file, then I receive only 1st part of the recording(before pause). I suppose that the proper audio file extension should be 3gp as this extension is used in the implementation of 'cordova-plugin-media' but then I have problems with playing this file using html audio tag. Any help is appriciated

回答1:

okay, I just found out that you can use method "resolveLocalFilesystemUrl" of the cordova-plugin-file which will return you the object and inside this object there is a property "nativeURL" which can be used as a source(src) for the video tag(had to video tag instead of audio because 3gp format is actually for video)



回答2:

this.file.readAsDataURL(filePathtoUpload, this.fileName)
.then((base64Audio) => {
console.log(base64Audio);
})
.catch(function (err: TypeError) {
console.log("readAsDataURL: " + err);
});

this works for me



回答3:

Read this:https://ionicframework.com/docs/v3/native/base64/

It is the oficial website API of ionic. Just install that plugin and use this:

 this.base64.encodeFile(this.filePath + this.fileName).then(
      (base64:any) =>{
      console.log('file base64 encoding: ' + base64);
    });

In this post, i explain it better. I let the link here: convert audio file to base64 in ionic 3