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();
}
}
I call AudioRecord
and AudioTrack
inside - onCreate
. When button "Rec" pushed it call: startRecord
and inside this method CoundownTimer
is created. CoundownTimer
stops this record after 10 sec. I write this record into the inner buffer. Then I'm trying to play this record by rewriting and playing it. What is wrong with this code?
I can't understand why "Play" is not working.