Encode Audio Byte[] Array to an Mp3 File – Android Studio

0
692

in this tutorial, i would put you through the step by step process you can encode audio byte arrays to an mp3 file. You need to understand clearly that the Android Sdk does not provide support for mp3 encoding (https://developer.android.com/guide/topics/media/media-formats). The sdk only supports mp3 decoding in which we would talk about in the next tutorial series.
To achieve mp3 encoding in Android studio, you have to either go Native using Android Studio NDk or use a Java wrapper library of a C/C++ library.

 

Important Digital Audio Terms You need to know:

These are the important terms you need to know if you are building an audio manipulation app on android studio.

PCM (pulse-code modulation) – This is the process of converting or representing physical audio signals to arrays of numbers. All audio sounds and music you listened to can be represented with numbers at specific moment of time.

Samples – When pcm is carried out on audio data, the audio data is represented in an array of numbers, a particular number is known as a sample.

Sampling rate – This is the number of samples per second.The most commonly used ones includes 44100 Hz. Sampling rate is the number of samples taken from a pcm audio data in 1 second.

Resolution/sample size/bit Size – This is the size of the variable number used in representing a sample. For example, Using an 8 bit integer number, you can represent 256 levels of amplitude.

Channels – Audio channels represents how sounds comes out of an audio speaker. it can be mono (1 channel) or stereo (2 channels). a single speaker can accept only one channel of audio.

 

Android NDK allows us write our codes in native languages like c / c++. Writing native language codes can be very hard for most people especially for beginners, but the good news is that we would be using an NDK wrapper java library instead, it is a wrapper of the popular lame mp3 encoding library (https://lame.sourceforge.io/) used by popular apps like Audacity, etc for mp3 encoding.

The java library we would be using can be fount here -> https://github.com/nwaldispuehl/java-lame. To use the library, you need to download and import the .jar java library which can be found here -> https://github.com/nwaldispuehl/java-lame/releases/download/v3.98.4/net.sourceforge.lame-3.98.4.jar

 

Also for the Audioformats method, you need to import this javax.sound.sampled.AudioFormat, you can download the jar at https://jar-download.com/maven-repository-class-search.php?search_box=javax.sound.sampled.AudioSystem

public void encodePcmToMp3(byte[] pcm) {
//        LameEncoder encoder = new LameEncoder(new javax.sound.sampled.AudioFormat(44100.0f, 16, 2, true, false), 256, MPEGMode.STEREO, Lame.QUALITY_HIGHEST, false);

    //fast  gmm2  LameEncoder encoder = new LameEncoder(new javax.sound.sampled.AudioFormat(88200.0f, 16, 2, true, false), 256, MPEGMode.STEREO, Lame.QUALITY_HIGHEST, false);

        LameEncoder encoder = new LameEncoder(new javax.sound.sampled.AudioFormat(44100.0f, 16, 2, true, false), 256, MPEGMode.STEREO, Lame.QUALITY_HIGHEST, false);


        ByteArrayOutputStream mp3 = new ByteArrayOutputStream();
        byte[] buffer = new byte[encoder.getPCMBufferSize()];

        int bytesToTransfer = Math.min(buffer.length, pcm.length);
        int bytesWritten;
        int currentPcmPosition = 0;

         while (0 < (bytesWritten = encoder.encodeBuffer(pcm, currentPcmPosition, bytesToTransfer, buffer))) {
            currentPcmPosition += bytesToTransfer;
            bytesToTransfer = Math.min(buffer.length, pcm.length - currentPcmPosition);
            Log.e("logmessage", "current position: " + currentPcmPosition);
            mp3.write(buffer, 0, bytesWritten);
        }

        encoder.close();

        File file = new File("/storage/emulated/0/bajj/gtmm5.mp3");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("logmessage", "cannot create file");
            }

            FileOutputStream stream = null;
            try {
                stream = new FileOutputStream("/storage/emulated/0/bajj/gtmm5.mp3");
                stream.write(mp3.toByteArray());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
     //   return mp3.toByteArray();
    }

LEAVE A REPLY

Please enter your comment!
Please enter your name here