1
我用一個非常簡單的任務創建了以下程序:錄製並顯示音頻。我試圖添加另一種方法,讓我以圖形方式顯示記錄的樣本。要做到這一點,我使用@Robby池塘在這個問題的其他一年前所做的一個建議:如何將音頻文件轉換爲字節
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-在嘗試執行那部分代碼時破壞了?我是用錯誤的方法打開文件或類似的東西?
非常感謝您的幫助!
我的目標是使用的值到緩衝區吸引他們,這樣我就可以有聲音我的圖形表示生成。 –
fileContent的類型? –