我正在尝试使用 Speex 库解码 Speex 编码的音频文件,但我总是得到ArrayIndexOutOfBoundsException
JNIEXPORT jint JNICALL Java_com_app_shared_Speex_decode
(JNIEnv *env, jobject obj, jbyteArray encoded, jshortArray lin, jint size) {
jbyte buffer[dec_frame_size ];
jshort output_buffer[dec_frame_size ];
jsize encoded_length = size;
if (!codec_open)
return 0;
env->GetByteArrayRegion(encoded, rtp_header, encoded_length, buffer);
/*
jboolean isCopy;
jbyte* data = env->GetByteArrayElements(encoded, &isCopy);
if(isCopy){
memcpy(buffer, data, encoded_length);
env->ReleaseByteArrayElements(encoded, data, JNI_ABORT);
}
*/
speex_bits_read_from(&dbits, (char *)buffer, encoded_length);
speex_decode_int(dec_state, &dbits, output_buffer);
std::string bufStr;
for(int i=0; i<20; i++){
char buff[100];
sprintf(buff, "Speex test %d => %d", i, output_buffer[i]);
bufStr = buff;
LOGI(bufStr.c_str());
}
bufStr = "before SetShortArrayRegion";
LOGI(bufStr.c_str());
(env)->SetShortArrayRegion(lin, rtp_header, dec_frame_size, output_buffer);
bufStr = "after SetShortArrayRegion";
LOGI(bufStr.c_str());
return (jint)dec_frame_size;
}
我得到:
SharedSpeex before SetShortArrayRegion
dalvikvm JNI WARNING: JNI method called with exception pending
dalvikvm in Lcom/company/shared/Speex;.decode:([B[SI)I (SetShortArrayRegion)
dalvikvm Pending exception is:
dalvikvm java.lang.ArrayIndexOutOfBoundsException: [B offset=12 length=1634 src.length=1634
有趣的一点是,如果我完全注释包含 的行SetShortArrayRegion
,则在退出范围时会发生异常:
SharedSpeex before SetShortArrayRegion
SharedSpeex after SetShortArrayRegion
AndroidRuntime Shutting down VM
dalvikvm threadid=1: thread exiting with uncaught exception (group=0xa62ca288)
AndroidRuntime FATAL EXCEPTION: main
AndroidRuntime java.lang.ArrayIndexOutOfBoundsException: [B offset=12 length=1634 src.length=1634
在官方JNI文档中,它显然更喜欢它,GetByteArrayRegion
而不是GetByteArrayElements
因为:
- 降低程序员出错的风险——没有在失败后忘记调用 Release 的风险。