I am trying to save an audio and send it to the server in ionic 3.
record(){
if (this.platform.is('ios')) {
this.fileName = 'record'+new Date().getDate()+new Date().getMonth()+new
Date().getFullYear()+new Date().getHours()+new Date().getMinutes()+new
Date().getSeconds()+'.3gp';
this.filePath = this.file.documentsDirectory.replace(/file:\/\//g, '') +
this.fileName;
this.audio = this.media.create(this.filePath);
} else if (this.platform.is('android')) {
this.fileName = 'record'+new Date().getDate()+new Date().getMonth()+new
Date().getFullYear()+new Date().getHours()+new Date().getMinutes()+new
Date().getSeconds()+'.3gp';
this.filePath = this.file.externalDataDirectory.replace(/file:\/\//g, '')
+ this.fileName;
this.audio = this.media.create(this.filePath);
}
this.audio.startRecord();
this.recording = true;
}
After stopping the record i want to send the audio file in base64 to the server. so I am using the base64 plugin to convert the audio file to base64.
this.base64.encodeFile(this.filePath).then((base64File: string) => {
// let audiooo = encodeURIComponent(base64File);
this.sendVoice(encodeURIComponent(base64File));
}, (err) => {
console.log(err);
});
However, using this plugin i get base64File with the below value:
data%3Aimage%2F%3Bcharset%3Dutf-8%3Bbase64%2C%2f%2FFsQBIF%2FAFAC....
I cannot play this encoded audio after sending it to the server, i believe it is because the file starts data%3Aimage... not with data%3Aaudio...
So any idea what am i doing wrong?
You could achieve this using FileReader.readAsDataURL():
I have different solution for this! as the basic native bas64 was not working properly
Solution
I have this amazing library that I used before to do audio conversion to base 64
//Encode Audio MP3 to Base64 var pathToFile = "/pathToFile/audio.mp3";
Use my answer in this post. It is an official library. Ionic 3 get base64 audio string from recorded file
To add the plugin in your project:
ionic cordova plugin add com-badrit-base64
to add the pluggin.npm install @ionic-native/base64
to add the module in your proyect and your package.jsonImport in your
module.ts
importing the libary like:import { Base64 } from "@ionic-native/base64";
Add it in the providers JSON.
Declare this new library in constructor of your component:
private base64:Base64,
Use the method.