我目前正在尝试创建一个将麦克风从麦克风循环到耳机的Android应用程序,我可以完美地做到这一点,但是当我在我的应用程序中反复执行时,我最终会出现Out of Memory Error。
以下是我用来创建音频循环的代码:
static final int bufferSize = 200000;
final short[] buffer = new short[bufferSize];
short[] readBuffer = new short[bufferSize];
public void run() {
isRecording = true;
android.os.Process.setThreadPriority
(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
int buffersize = AudioRecord.getMinBufferSize(11025,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_16BIT);
arec = new AudioRecord(MediaRecorder.AudioSource.MIC,
11025,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
MediaRecorder.AudioEncoder.AMR_NB,
buffersize);
atrack = new AudioTrack(AudioManager.STREAM_VOICE_CALL,
11025,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
MediaRecorder.AudioEncoder.AMR_NB,
buffersize,
AudioTrack.MODE_STREAM);
Log.d("AUDIO", "sample rate = : " + arec.getSampleRate());
atrack.setPlaybackRate(11025);
byte[] buffer = new byte[buffersize];
arec.startRecording();
atrack.play();
while(isRecording) {
arec.read(buffer, 0, buffersize);
atrack.write(buffer, 0, buffer.length);
}
}
这是我得到的错误:
ERROR/AndroidRuntime(3442): Uncaught handler: thread main exiting due to uncaught exception
ERROR/AndroidRuntime(3442): java.lang.OutOfMemoryError
ERROR/AndroidRuntime(3442): at com.phone.engine.CallAudio$Record.<init>(CallAudio.java:114)
ERROR/AndroidRuntime(3442): at com.phone.engine.CallAudio.onCreate(CallAudio.java:42)
ERROR/AndroidRuntime(3442): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2465)
ERROR/AndroidRuntime(3442): at android.app.ActivityThread.access$2800(ActivityThread.java:112)
ERROR/AndroidRuntime(3442): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1744)
ERROR/AndroidRuntime(3442): at android.os.Handler.dispatchMessage(Handler.java:99)
ERROR/AndroidRuntime(3442): at android.os.Looper.loop(Looper.java:123)
ERROR/AndroidRuntime(3442): at android.app.ActivityThread.main(ActivityThread.java:3948)
ERROR/AndroidRuntime(3442): at java.lang.reflect.Method.invokeNative(Native Method)
ERROR/AndroidRuntime(3442): at java.lang.reflect.Method.invoke(Method.java:521)
ERROR/AndroidRuntime(3442): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
ERROR/AndroidRuntime(3442): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
ERROR/AndroidRuntime(3442): at dalvik.system.NativeStart.main(Native Method)
因此,错误特别关注代码中的这一行
short[] readBuffer = new short[bufferSize];
它发生在我尝试循环几次之后,所以说我启动应用程序并且在启动循环10次之后我得到了错误。
所以我认为缓冲区只是简单地充满了什么?那是对的吗?如果是这样,我将如何清除缓冲区?
提前致谢