在Manifest要記得將錄音以及寫入內部SD卡權限打開
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
package com.example.androidrecoder;
import....
public class MainActivity extends Activity {
//MediaRecorder物件
MediaRecorder recorder;
String filepath="/abcd/";
String filename="audio.3gp";
File file;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Environment.getExternalStorageDirectory()傳回File物件,
//File.getAbsolutePath()取得SD卡路徑字串
String sdcardpath=Environment.getExternalStorageDirectory().getAbsolutePath();
//建立存放錄音檔的資料夾
if(!new File(sdcardpath+filepath).exists()){
new File(sdcardpath+filepath).mkdir();
Toast.makeText(this, "建立資料夾...", Toast.LENGTH_SHORT).show();
}
file=new File(sdcardpath+filepath+filename);
}
public void but1_onclick(View V){
recorder=new MediaRecorder();
//設定聲音來源
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
//設定輸出錄音檔格式
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
//設定錄音檔存放位置
recorder.setOutputFile(file.getAbsolutePath());
//設定錄音的編碼方式
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
// prepare()完成錄音之準備工作,必須在try catch下完成
try {
recorder.prepare();
recorder.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void but2_onclick(View V){
//記得停止撥放時要釋放資源
if(recorder!=null){
recorder.stop();
recorder.release();
}
}
}
沒有留言:
張貼留言