我创建了以下程序,其任务非常简单:录制然后显示音频。我试图添加另一种方法,允许我以图形方式显示记录的样本。为此,我使用了一年前@Robby Pond 在另一个问题中提出的建议:
http://stackoverflow.com/questions/5333908/fileinputstream-to-byte-array-in-android-application
我的活动的核心是这样的:
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class RecorderTutorial extends Activity implements OnClickListener{
MediaRecorder mRecorder = new MediaRecorder();
MediaPlayer mPlayer = new MediaPlayer();
boolean isRecording = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recorder_tutorial);
findViewById(R.id.play_back_button).setOnClickListener(this);
findViewById(R.id.record_button).setOnClickListener(this);
findViewById(R.id.draw).setOnClickListener(this);
}
public void onClick(View v) {
mPlayer.stop();
switch (v.getId()) {
case R.id.play_back_button:
if (!isRecording && !mPlayer.isPlaying()) {
try {
mPlayer.reset();
mPlayer.setDataSource("/sdcard/audio_demo.3gp");
mPlayer.prepare();
mPlayer.start();
} catch (Exception e) {
Toast.makeText(this, "Error playing back audio.",Toast.LENGTH_SHORT).show();
}
}
break;
case R.id.record_button:
if (isRecording) {
isRecording = false;
((Button)(findViewById(R.id.record_button))).setText("record");
mRecorder.reset();
} else {
try {
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile("/sdcard/audio_demo.3gp");
mRecorder.prepare();
mRecorder.start();
((Button)(findViewById(R.id.record_button))).setText("stop");
isRecording = true;
} catch (Exception e) {
Toast.makeText(this, "Error starting recorder.",Toast.LENGTH_SHORT).show();
}
}
break;
case R.id.draw:
final Context context = v.getContext();
int bytesRead;
try {
InputStream is = context.openFileInput("/sdcard/audio_demo.3gp");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();
System.out.println(" One random values is: "+bytes[5]+" \n");
}catch(Exception e) {
Toast.makeText(this, "Error starting draw. ",Toast.LENGTH_SHORT).show();
}
break;
}
}
@Override
public void onDestroy() {
if (isRecording) {
Toast.makeText(this, "Recorder stopped.",Toast.LENGTH_SHORT).show();
mRecorder.stop();
}
mRecorder.release();
mPlayer.stop();
mPlayer.release();
super.onDestroy();
}
}
谁能告诉我为什么第三个选项 -R.id.draw case- 在我执行那部分代码时会在尝试中中断?我是否以错误的方法打开文件或类似的东西?
非常感谢您的帮助!