public class MainActivity extends AppCompatActivity {
static int SAMPLE_RATE_44100 = 44100;
AudioRecord audioRecord;
AudioTrack audioTrack;
CountDownTimer countdownTimer;
TextView textView_coundown_timer_display;
int bufferSize = 882000; // 44100*16*1/8*10
byte [] mediabuffer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView_coundown_timer_display = (TextView) findViewById.id.textView_coundown_timer_display);
mediabuffer = new byte[bufferSize];
createAudioRecord();
Log.d("audiorec", "state " + audioRecord.getState());//0 - STATE_UNINITIALIZED, 1 - STATE_INITIALIZED, 2 - STATE_NO_STATIC_DATA
createAudiotrack();
Log.d("audiotrack", "state " + audioTrack.getState()); //0 - STATE_UNINITIALIZED, 1 - STATE_INITIALIZED, 2 - STATE_NO_STATIC_DATA
}
void createAudioRecord () {
audioRecord = new AudioRecord(
MediaRecorder.AudioSource.MIC,
SAMPLE_RATE_44100,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
AudioRecord.getMinBufferSize(
SAMPLE_RATE_44100,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT)*10);
}
public void createAudiotrack () {
audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC,
SAMPLE_RATE_44100,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT,
bufferSize,
AudioTrack.MODE_STREAM);
audioTrack.setPlaybackRate(SAMPLE_RATE_44100);}
}
public void startRead(){
new Thread(new Runnable() {
@Override
public void run() {
audioRecord.read(mediabuffer, 1, bufferSize);
Toast.makeText(getApplicationContext(), "reading" + audioRecord.getState(), Toast.LENGTH_SHORT ).show();
}
}).run();
}
public void audiotrackWriteAndPlay (View view) {
audioTrack.write(mediabuffer, 1, bufferSize);
Toast.makeText(getApplicationContext(), "writing" , Toast.LENGTH_SHORT ).show();
audioTrack.play();
}
public void stopRecord (){
audioRecord.stop();
Toast.makeText(getApplicationContext(), "mediabuffer lenght"+mediabuffer.length, Toast.LENGTH_SHORT).show();
}
void recordTimer(){
countdownTimer = new CountDownTimer(10000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
textView_coundown_timer_display.setText(millisUntilFinished/1000+"");
}
@Override
public void onFinish() {
textView_coundown_timer_display.setText("0");
stopRecord();
startRead();
}
}.start();
}
}
我在AudioRecord
内调用AudioTrack
和onCreate
。按钮" Rec"推动它调用:startRecord
并在此方法CoundownTimer
内创建。 CoundownTimer
在10秒后停止此记录。我把这条记录写入内部缓冲区。然后我试图通过重写和播放来播放这个记录。这段代码有什么问题?
我无法理解为什么" Play"没有用。