Search This Blog

Sunday, March 20, 2016

VIẾT ỨNG DỤNG GHI ÂM

Bước 1: Lấy Permissions
< uses-permission android:name="android.permission.RECORD_AUDIO" />
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Bước 2: MainActivity:
1. Biến toàn cục:
private MediaRecorder myRecorder;
private MediaPlayer myPlayer;
private String outputFile = null;
2. Hàm OnCreate:
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/khoaphamvn.3gpp";
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
Bước 3: Các hàm xử lý:
1. Bắt đầu ghi âm
public void start(View view){
    try {
        myRecorder.prepare();
        myRecorder.start();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Toast.makeText(getApplicationContext(), "Start recording...",
            Toast.LENGTH_SHORT).show();
}
2. Dừng ghi âm
public void stop(View view){
    try {
        myRecorder.stop();
        myRecorder.release();
        myRecorder  = null;

        Toast.makeText(getApplicationContext(), "Stop recording...",
                Toast.LENGTH_SHORT).show();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (RuntimeException e) {
        e.printStackTrace();
    }
}
3. Play âm thanh đã thu
public void play(View view) {
    try{
        myPlayer = new MediaPlayer();
        myPlayer.setDataSource(outputFile);
        myPlayer.prepare();
        myPlayer.start();

        Toast.makeText(getApplicationContext(), "Start play the recording...",Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
4. Dừng Play:
public void stopPlay(View view) {
    try {
        if (myPlayer != null) {
            myPlayer.stop();
            myPlayer.release();
            myPlayer = null;

            Toast.makeText(getApplicationContext(), "Stop playing the recording...", Toast.LENGTH_SHORT).show();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

No comments:

Post a Comment