开发者

How to Store Audio into buffer and then reading it byte by byte

I开发者_StackOverflow can make wav file by MediaRecord of android ...but I am interested to put the audio data in a buffer and read it byte by byte...I have to send audio chunks byte wise over TCP channel....Can any one help me please...thanks in advance,

szaman from austria


You can use AudioRecord to read the audio data byte by byte, here is some sample code.

// calculate the minimum buffer
int minBuffer = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT);

// initialise audio recorder and start recording
AudioRecord mRec = new AudioRecord(AUDIO_SOURCE, SAMPLE_RATE, 
                CHANNEL_CONFIG, AUDIO_FORMAT, 
                minBuffer);
mRec.startRecording();
byte[] pktBuf = new byte[pktSizeByte];
boolean ok;
// now you can start reading the bytes from the AudioRecord
while (!finished) {
    // fill the pktBuf
    readFully(pktBuf, 0, pktBuf.length);
    // make a copy
    byte[] pkt = Arrays.copyOf(pktBuf, pktBuf.length);
    // do anything with the byte[] ...
}

Since a single call to read() might not get enough data to fill the byte[] pktBuf, we might need to read multiple times to fill the buffer. In this case, I use an auxiliary function "readFully" to ensure the buffer is filled. Depending what you want to do with your code, different strategy can be used...

/* fill the byte[] with recorded audio data */
private void readFully(byte[] data, int off, int length) {
    int read;
    while (length > 0) {
        read = mRec.read(data, off, length);
        length -= read;
        off += read;
    }
}

Remember to call mRec.stop() to stop the AudioRecorder after finished. Hope that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜