i hava a byte array which i am able to play successfully with AudioTrack. I am trying to encode or convert the byte array to an mp3 file. Since Android sdk doesnt support mp3 encoding, i am using Lame via this library (https://github.com/nwaldispuehl/java-lame). The Output mp3 plays noise only.
public void encodePcmToMp3(byte[] pcm) {
LameEncoder encoder = new LameEncoder(new javax.sound.sampled.AudioFormat(44100.0f, 16, 1, true, true), 256, MPEGMode.MONO, 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/gtm.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/gtm.mp3");
stream.write(mp3.toByteArray());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// return mp3.toByteArray();
}
The Output mp3 plays noise only.