android怎样录制系统内部声音
通过API 19新加的MediaRecorder.AudioSource.REMOTE_SUBMIX参数可以让系统App录制系统内置的声音,也就是扬声器的声音。下面是一个巨简单的例子来示例如何通过AudioRecord配合REMOTE_SUBMIX参数进行录制。
1. 编译apk
MainActivity.java:
package com.example.audiotest;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private static String TAG = "JZJ";
AudioRecord mRecord = null;
boolean mReqStop = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
(new Thread() {
@Override
public void run() {
recordAndPlay();
}
}).start();
}
private final int kSampleRate = 44100;
private final int kChannelMode = AudioFormat.CHANNEL_IN_STEREO;
private final int kEncodeFormat = AudioFormat.ENCODING_PCM_16BIT;
private void init() {
int minBufferSize = AudioRecord.getMinBufferSize(kSampleRate, kChannelMode,
kEncodeFormat);
mRecord = new AudioRecord(MediaRecorder.AudioSource.REMOTE_SUBMIX,
kSampleRate, kChannelMode, kEncodeFormat, minBufferSize * 2);
}
private final int kFrameSize = 2048;
private String filePath = "/sdcard/voice.pcm";
private void recordAndPlay() {
FileOutputStream os = null;
mRecord.startRecording();
try {
os = new FileOutputStream(filePath);
byte[] buffer = new byte[kFrameSize];
int num = 0;
while (!mReqStop) {
num = mRecord.read(buffer, 0, kFrameSize);
Log.d(TAG, "buffer = " + buffer.toString() + ", num = " + num);
os.write(buffer, 0, num);
}
Log.d(TAG, "exit loop");
os.close();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Dump PCM to file failed");
}
mRecord.stop();
mRecord.release();
mRecord = null;
Log.d(TAG, "clean up");
}
public void stop(View view) {
mReqStop = true;
Button stopBtn = (Button) findViewById(R.id.stopBtn);
stopBtn.setText("Stopped");
stopBtn.setEnabled(false);
}
}