ByteBuffer.array()返回一个比ByteBuffer Android更大的数组



基本上我有以下场景:

inputByteBuffer (capacity in debug) => 1024
byte[] inByteBufferArray = inputByteBuffer.array();
inByteBufferArray.length => 1031 ????

ByteBuffer数组()方法说它"返回这个缓冲区所基于的字节数组,如果有的话。"ref

这是工作在Android API 18,有什么变化吗?有一个ByterBuffer arrayOffset()方法,我需要它吗?

这发生在Nexus 6设备上,但我认为这无关紧要。

感谢

private static int bufferSizeStatic = 1024;
private float[] Read(){
        mAudioRecord.read(inputByteBuffer, bufferSize);
        return readByteArray(inputByteBuffer.array(), inputByteBuffer.arrayOffset());
}
private float[] readByteArray(byte[] byteArray, int offSet) {
        if (floatArray == null || floatArray.length!=(byteArray.length-offSet) / (numChannels*numBytePerFrame)){
            floatArray = new float[(byteArray.length-offSet) / (numChannels*numBytePerFrame)];
        }
        if (numChannels == 1){
            for (int i = 0; i < floatArray.length; i++){
                short tempShort = (short) ((byteArray[2*i+1+offSet]<<8) + byteArray[2*i+offSet]);
                floatArray[i] = (float) (tempShort / Math.pow(2,15)); 
            } 
        } //TODO add stereo support
        return floatArray;
    }   

我不明白你为什么在乎。您的代码当然不应该在意。唯一的原因是你滥用了API。您不应该从不在缓冲区中的缓冲区中获取数据,这是由limit(),而不是由array().length()capacity()提供的。

您所需要做的就是调整调用顺序并直接使用ByteBuffer

private static int bufferSizeStatic = 1024;
private float[] Read(){
    // I don't know why you need to pass `bufferSize` here: `inputByteBuffer` already knows its own limit
        mAudioRecord.read(inputByteBuffer, bufferSize);
        return readByteArray(inputByteBuffer);
}
private float[] readByteArray(ByteBuffer byteBuffer) {
        if (floatArray == null || floatArray.length!=(byteArray.limit()-byteArray.position()) / (numChannels*numBytePerFrame)){
            floatArray = new float[(byteArray.limit()-byteArray.position()) / (numChannels*numBytePerFrame)];
        }
        byteBuffer.flip();
        if (numChannels == 1){
            for (int i = 0; i < floatArray.length; i++){
                short tempShort = (short) ((ByteBuffer.getShort(i*2));
                floatArray[i] = (float) (tempShort / 32768.0); 
            } 
        } //TODO add stereo support
        byteBuffer.compact();
        return floatArray;
    }   

E&OE-

你会发现这至少同样有效。

我发现了android代码:

MemoryRef(int capacity) {
    VMRuntime runtime = VMRuntime.getRuntime();
    buffer  = (byte[])runtime.newNonMovableArray(byte.class, capacity + 7);
    allocatedAddress = runtime.addressOf(buffer);
    // Offset is set to handle the alignment: http://b/16449607
    offset = (int)(((allocatedAddress + 7) & ~(long)7) - allocatedAddress);
    isAccessible = true;
}

此处的来源:https://android.googlesource.com/platform/libcore/+/fe0e555d3e460de87d24e0224ef10b089289355c47/ojluni/src/main/java/java/nio/DirectByteBuffer.java#60

最新更新