Farman Ali Khan
Farman Ali Khan

Reputation: 896

Recording audio in .mp3 format by using AudioRecord

I want to record and save audio in .mp3 format using AudioRecord class. Currently it is recording in .pcm format. I have used below code for record -

  private void writeAudioDataToFile() {
    // Write the output audio in byte

    String filePath = "/sdcard/voice8K16bitmono.pcm";
    short sData[] = new short[BufferElements2Rec];

    FileOutputStream os = null;
    try {
        os = new FileOutputStream(filePath);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    while (isRecording) {
        // gets the voice output from microphone to byte format

        m_audioRecord.read(sData, 0, BufferElements2Rec);
        System.out.println("Short wirting to file" + sData.toString());
        try {
            // // writes the data to file from buffer
            // // stores the voice buffer

            byte bData[] = short2byte(sData);

            os.write(bData, 0, BufferElements2Rec * BytesPerElement);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        os.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

   private byte[] short2byte(short[] sData) {
    int shortArrsize = sData.length;
    byte[] bytes = new byte[shortArrsize * 2];

    for (int i = 0; i < shortArrsize; i++) {
        bytes[i * 2] = (byte) (sData[i] & 0x00FF);
        bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
        sData[i] = 0;
    }
    return bytes;

}

Above two method is for recording file in .pcm format. Is this possible to save audio in .mp3 format using AudioRecord class?

Upvotes: 2

Views: 2054

Answers (1)

Samir Bhatt
Samir Bhatt

Reputation: 3261

There is no encoder that record file in mp3 available in android. You can not achieve mp3 using native functionality. You can use any third party library to achieve this.

Check this post, which may help you.

Upvotes: 1

Related Questions