Converting an audio file into base64 format using Ionic 3

I'm currently working on a project in Ionic 3 where I need to record audio and send it to the server.

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;
}

Once the recording is done, my next step is to convert the audio file to base64 and send it to the server. For this conversion, I am utilizing the base64 plugin.

this.base64.encodeFile(this.filePath).then((base64File: string) => {
            // let audiooo = encodeURIComponent(base64File);
            this.sendVoice(encodeURIComponent(base64File));
        }, (err) => {
          console.log(err);
        });

However, when trying to encode the file, I encounter an issue. The encoded value starts with data%3Aimage..., instead of data%3Aaudio... which prevents me from playing the audio after sending it to the server.

data%3Aimage%2F%3Bcharset%3Dutf-8%3Bbase64%2C%2f%2FFsQBIF%2FAFAC....

Do you have any insights on what might be causing this problem? 

Answer №1

Feel free to use my solution provided in this discussion thread. It comes from an authoritative source. Click here for more details.

To integrate the plugin into your project, follow these steps:

  1. Run the command:
    ionic cordova plugin add com-badrit-base64
    to install the plugin.
  2. Execute:npm install @ionic-native/base64 to include the module in your project and package.json file.
  3. In your module.ts, import the library as follows:

    import { Base64 } from "@ionic-native/base64";

  4. Add it to the providers list in your JSON configuration.

    providers:[
          Camera,
          Media,
          File,
          SpeechRecognition,
          Base64,
    ],
    
  5. Declare the new library in the constructor of your component:private base64:Base64,

  6. Utilize the method below to achieve the desired functionality.

    this.base64.encodeFile(this.filePath + this.fileName).then(
    (base64:any) =>{
      console.log('file base64 encoding: ' + base64);
      var x = base64.substr(13,base64.length);
      x = "data:audio/mpeg;base64" + x;
    });
    

Answer №2

After encountering issues with the basic native base64 encoding, I found an alternative solution that worked perfectly!

Here is the solution:

I came across this fantastic library that I had used in the past for converting audio to base64 format:
//Encoding Audio MP3 to Base64 var pathToFile = "/pathToFile/audio.mp3";

Base64ToAudio.readAudio(pathToFile, 
    function(sourceAudio)
    {
        console.log(sourceAudio) //Returns Base64 String
    },
    function(error)
    {
        console.log(error);
    }
);

//Decoding Audio MP3 from Base64 and saving the file onto storage.
var conf = { "b64string": sourceAudio, "filename": "new-voice.mp3", "folder": "/pathToDirectory/", "overwrite": true };

Base64ToAudio.saveAudio(conf,
    function(success){
        console.log(success); //Returns 'OK' when the file is successfully generated.
    },
    function(error){
        console.log(error);
    }
);

Answer №3

To accomplish this task, you can utilize the FileReader.readAsDataURL() method:

const fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = () => {
  const base64String = fileReader.result // This is your base64 data.
}

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

Enhanced URL Routing Implemented on GitHub Pages Post-Deployment (Angular)

I recently developed a website using Angular (v8) and am currently facing an issue while trying to deploy it on a custom domain through github pages. The deployment is successful at www.changethenarrativeproject.com, but upon visiting the site, it automati ...

Retrieve the ngModel's current value

One of the challenges I encountered is with a textarea and checkbox interaction. Specifically, once the checkbox is checked, I aim to have the value appear in the textarea. <div class="message-container"> <textarea *ngIf="mode === 1" ...

Error occurs in Ionic 2 when attempting to make an Http request on a device, resulting in a net::ERR_CONNECTION

NOTE: For a detailed explanation, check out this Ionic Forum thread While the app functions perfectly when using ionic serve and is able to communicate over HTTPS with remote servers and the Google Maps API server through appropriate proxy settings, any r ...

The argument passed cannot be assigned to the parameter required

Currently, I am in the process of transitioning an existing React project from JavaScript to TypeScript. One function in particular that I am working on is shown below: const isSad = async (value: string) => { return await fetch(process.env.REACT_AP ...

Retrieving the parent object of a nested object within a JSON data structure using TypeScript

Is there a way to programmatically retrieve the parent object from a child object? My goal is to dynamically access the value of a property that belongs to the parent of a child object. For instance, in the given JSON data, I am interested in getting the ...

How can I limit props.children in a React TypeScript component?

import React from 'react'; import './App.css'; import Message from "./components/Message"; function App() { return ( <div className="App"> <Message> <p>Hello ...

Having trouble with installing Typescript on a MacBook?

I have been attempting to follow the instructions provided on TypeScriptLang.org but for some reason, I am unable to successfully download typescript. This is what I have tried so far: mkotsollariss-MacBook-Pro:/ mkotsollaris$ which node /usr/local/bin/n ...

Ensure data is only fetched in Ngrx if the store is empty

In my application, there are a total of 3 pages: Faculties, Groups, and Specialties. Here is how the interface for these entities is structured: interface Faculty { faculty_id: number; faculty_name: string; faculty_description: string; } interface S ...

Dynamically altering the CSS4 variables in real time

I am facing the challenge of managing multiple CSS4 variables, including primary, for various companies. How can I dynamically change the primary CSS4 variable color based on the company? Note: My specific requirement is to update the primary variable glo ...

Imitate a worldwide entity with Jest and Typescript

I have a React component that utilizes the global object Routes provided by the Rails gem js-routes. My component is being tested with Jest's snapshot testing feature. The issue arises when trying to mock the Routes global object in the test to return ...

Angular 2 Return {responseBody: "assigned variable with [object Object]"}

In my Angular 2 application, I am encountering an issue where I am sending a variable from a service to a component. In the template, the variable appears as expected, however, when attempting to send this variable to a PHP script using POST, I receive [ ...

Trying out the results of angular services

Seeking assistance in understanding the current situation: I believe a simple tour of heroes app would be helpful in clarifying, I am looking to set up some tests using Jest to verify if the behavior of a service remains consistent over time. This is ho ...

Angular Dropdown with Extensive Data Collection

My angular app is utilizing firebase to search through a large dataset. I need to present a dropdown menu to the user containing around 20k objects. What are some effective strategies for handling this task without sacrificing performance? I've expe ...

Incorporate personalized No Data Available message in ngx-datatable

How can I customize the no data message for ngx-datatable? I want to avoid displaying the default message that comes with it. Here is what I have attempted so far: <div *ngIf="showTable"> <ngx-datatable [rows]="rows"> ...

Retrieve list of friend names along with their corresponding friend IDs from MongoDB

Creating a MEAN app for the first time and successfully inserting users into MongoDB. Each user entry includes: { "name":"My Name", "country":"Italy", "friends":"5922c66b4e708e27a02b7937" } First query: How can I manually add multiple friends (separate t ...

Issue with Angular caused by Bootstrap node module

I encountered an issue when trying to run ng serve, receiving an error related to my node_modules. I suspect that moving a file into another folder may have caused this problem, but I'm unsure how to resolve it. bootstrap node_module error Additiona ...

What is the best way to empty session storage in Angular when the browser tab is closed?

Every time I access my browsing history, it automatically logs me in. However, if I try to enter the URL in a new tab, I am redirected to the login page. I have already attempted to clear the session by using browser tab close events. // 1 @HostListener(&a ...

What could be the reason for the bootstrap carousel failing to load on Angular 17 SSR?

Using bootstrap, I copied a snippet from the bootstrap page and made some modifications to utilize @for because my image is coming from a service. Below is the code I used: <div class="container"> <div class="carousel"> ...

Is there a way to close a window in JavaScript that was opened using Ionic Capacitor?

Currently, I am trying to open a window within my Ionic app by using the code snippet below: await Browser.open({url: environment.apiUrl + `/myurl`}); However, upon completion of a certain action by the user, I want to close that same window. Unfortunate ...

Ensure that the MUI icon color is set accurately

I created a functional component to set default values for react-admin's BooleanField. Here is the code: import ClearIcon from '@mui/icons-material/Clear' import DoneIcon from '@mui/icons-material/Done' import get from ...