1. 要進行錄音需先取得錄音的許可權,加上需將錄音檔寫到記憶卡,因此需在AndroidManifest.xml允許存取android.permission.RECORD_AUDIO及android.permission.WRITE_EXTERNAL_STORAGE這二個許可權。

 

2.MediaRecorderExample.java
package tw.nicky;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;

 

public class MediaRecorderExample extends Activity {
private Button recordButn;
private Button stopButn;
private MediaRecorder mediaRecorder = null;

 

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
recordButn = (Button) findViewById(R.id.recordButn);
stopButn = (Button) findViewById(R.id.stopButn);

 

//錄音
recordButn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//設定錄音檔名
String fileName = "record.amr";
try {
File SDCardpath = Environment.getExternalStorageDirectory();
File myDataPath = new File( SDCardpath.getAbsolutePath() + "/download" );
if( !myDataPath.exists() ) myDataPath.mkdirs();
File recodeFile = new File(SDCardpath.getAbsolutePath() + "/download/"+fileName);

 

mediaRecorder = new MediaRecorder();

 

//設定音源
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
//設定輸出檔案的格式
mediaRecorder
.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
//設定編碼格式
mediaRecorder
.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
//設定錄音檔位置
mediaRecorder
.setOutputFile(recodeFile.getAbsolutePath());

 

mediaRecorder.prepare();

 

//開始錄音
mediaRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
});

 

//停止錄音
stopButn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
}
}
});

 

}
}



3. main.xml(Layout)
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:id="@+id/widget0"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="HTTP://schemas.android.com/apk/res/android"
>
<Button
android:id="@+id/recordButn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="錄音"
android:layout_x="68px"
android:layout_y="44px"
&...
創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()