该APP主要功能是播放和录音。
但是使用Timer计时器实现在子线程中自动每次录5秒,共录33次。
player 为MediaPlayer对象。
在启动播放时使用player.start()
结束播放时使用player.stop()
然后不断开始结束
但是第二次时会出现报错MediaPlayer start called in state 0。
然后查了一下这个问题,就是如果是第一次用player这个对象开始播放时可以直接使用player.start()。
但是如果是循环使用的话,第二次开始需要在player.start()前面或者player.stop()后面添加player.prepare()。
但是我在该代码时,如果第一次用player.start()的话,在player.start()前面添加player.prepare()会产生异常。
因此为了避免判断是否第一次使用,建议多次使用player.start()时在player.stop()后面添加player.prepare()方法,在添加时会提示产生异常,因此还需要处理异常,下面是我的整个TimerTask代码:
class myTaskStart extends TimerTask{
@Override
public void run(){
//开始录音
System.out.println("启动程序");
//count为一个全局变量,该全局变量来控制run的运行次数
if(count<33){
count=count+1;
}
else {
this.cancel();
System.exit(0);
}
//结束使用count控制run的运行次数
//开始更新TextView里面的字符串
textView.post(new Runnable() {
@Override
public void run() {
textView.setText("start"+count);
}
});
//结束更新TextView里面的字符串
player.start();
String fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
audioRecorder.createDefaultAudio(fileName); // status = Status.STATUS_READY;
audioRecorder.startRecord(null);
//等待录音
try {
Thread.sleep(5000);
}
catch (InterruptedException e)
{
Toast.makeText(getApplicationContext(),"异常",Toast.LENGTH_LONG).show();
}
//停止录音
System.out.println("停止录音啊啊啊啊");
audioRecorder.stopRecord();
player.stop();
textView.post(new Runnable() {
@Override
public void run() {
textView.setText("end");
}
});
//在player.stop()后面添加player.prepare(),需要处理异常!
try {
player.prepare();
}
catch (IOException e)
{
System.out.println("player初始化失败!");
}
//结束添加player.prepare
}
}
主要代码如下:
player.stop();
//在player.stop()后面添加player.prepare(),需要处理异常!
try {
player.prepare();
}
catch (IOException e)
{
System.out.println("player初始化失败!");
}
//结束添加player.prepare
这样就可以正常运行了。