简体   繁体   中英

Compatibility of Android's AudioRecord with Java's SE AudioFormat

I am writing an Android application, which sends recorded sound to a server and I need to adapt its format to the one which is required. I was told that the server's audio format is specified by javax.sound.sampled.AudioFormat class constructor with the following parameters: AudioFormat(44100, 8, 1, true, true), which means that the required sound should have 44100 sample rate, 8 bit sample size, mono channel, be signed and encoded with big endian byte order. My question is how can I convert my recorded sound to the one I want? I think that the biggest problem might be Android's 16b restriction as far as the smallest sample size is concerned

You can record 44100 8bit directly by AudioRecord , specifying the format in the constructor

int bufferSize = Math.max(
    AudioRecord.getMinBufferSize(44100, 
        AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_8BIT),
    ENOUGH_SIZE_FOR_BUFFER);
AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, 
    44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_8BIT, bufferSize);

then pull data from audioRecord, using read(byte[], int, int) method:

byte[] myBuf = new byte[bufferSize];
audioRecord.startRecording();
while (audioRecord.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) {
    int l = audioRecord.read(myBuf, 0, myBuf.length);
    if (l > 0) {
        // process data
    }
}

in this case the data in the buffer will be as you want: 8 bit, mono, 44100.
But, some devices may not support 8 bit recording. In this case you can record the data in 16 bit format, and obtain it using read(short[], int, int) method. In this case you need to resample data on your own:

short[] recordBuf = new short[bufferSize];
byte[] myBuf = new byte[bufferSize];

...

    int l = audioRecord.read(recordBuf, 0, recordBuf.length);
    if (l > 0) {
        for (int i = 0; i < l; i++) {
           myBuf[i] = (byte)(recordBuffer[I] >> 8);
        }
        // process data
    }

Using the same approach, you can resample any PCM format to any another format;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM