Before 2022/Android

안드로이드 고음질 녹음

Eljoe 2019. 1. 31. 14:23
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;

import com.gun0912.tedpermission.PermissionListener;
import com.gun0912.tedpermission.TedPermission;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends Activity {
    private static final String permission = Manifest.permission.RECORD_AUDIO;

    private File file;
    private String fileName;

    private MediaRecorder recorder;
    private MediaPlayer mediaPlayer;

    //녹음
    @BindView(R.id.btn_record)
    Button mBtnRecord;

    //중지
    @BindView(R.id.btn_stop)
    Button mBtnStop;

    //재생
    @BindView(R.id.btn_play)
    Button mBtnPlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        //파일 경로 및 이름 지정
        fileName = Objects.requireNonNull(getExternalCacheDir()).getAbsolutePath();
        fileName += "/testRecord.3gp";

        //권한 체크
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            int permissionChceck = this.checkSelfPermission(permission);

            if (permissionChceck == PackageManager.PERMISSION_DENIED) {
                TedPermission.with(this)
                        .setPermissionListener(permissionListener)
                        .setPermissions(permission)
                        .check();
            }
        }

        mBtnRecord.setOnClickListener(v -> startRecording());
        mBtnStop.setOnClickListener(v -> stopRecording());
        mBtnPlay.setOnClickListener(v -> startPlay());
    }

    PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onPermissionGranted() {
        }

        @Override
        public void onPermissionDenied(List<String> deniedPermissions) {
            Toast.makeText(getApplicationContext(), "권한 허용 후 녹음 가능합니다.", Toast.LENGTH_SHORT).show();
            finish();
        }
    };

    private void startRecording() {
        recorder = new MediaRecorder();
        //오디오 입력 선택
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        //출력파일 확장자 지정
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        //샘플링 비율
        recorder.setAudioSamplingRate(44100);
        //비트레이트
        recorder.setAudioEncodingBitRate(96000);
        //인코딩 코덱 설정
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        //오디오 파일 출력
        recorder.setOutputFile(fileName);
        try {
            recorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        recorder.start();
    }

    private void stopRecording() {
        if (recorder != null) {
            file = new File(fileName);
            recorder.stop();
            recorder.release();
            recorder = null;
        } else {
            Toast.makeText(this, "녹음을 먼저 진행해주세요.", Toast.LENGTH_SHORT).show();
        }
    }

    private void startPlay() {
        //파일이 존재하는 경우 재생 시작
        if (file != null && file.exists()) {
            mediaPlayer = new MediaPlayer();
            try {
                mediaPlayer.setDataSource(fileName);
                mediaPlayer.prepare();
                mediaPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(this, "녹음을 먼저 진행해주세요.", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

        if (recorder != null) {
            recorder.release();
            recorder = null;
        }

        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    @Override
    protected void onDestroy() {
        //파일 삭제
        if (file != null && file.exists()) file.delete();
        super.onDestroy();
    }
}