반응형
오디오 녹음이나 동영상 녹화를 위해서는 MediaRecorder가 사용된다
매니페스트에 권한 설정
미디어리코더 객체 생성
오디오 입력 및 출력 형식 설정
오디오 인코더와 파일 지정
녹음 시작
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.a75_audiorecorder">
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:requestLegacyExternalStorage="true"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.A75_AudioRecorder">
<activity android:name=".MainActivity" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="녹음시작" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="녹음중지" />
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="재생시작" />
<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="재생중지" />
</LinearLayout>
MainActivitiy
package com.example.a75_audiorecorder;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.util.List;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
public class MainActivity extends AppCompatActivity {
MediaRecorder recorder;
MediaPlayer player;
File file;
String filename;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startRecording();
}
});
Button button2 = findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopRecording();
}
});
Button button3 = findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startPlay();
}
});
Button button4 = findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopPlay();
}
});
file = getOutputFile();
if (file != null) {
filename = file.getAbsolutePath();
}
AndPermission.with(this)
.runtime()
.permission(
Permission.RECORD_AUDIO,
Permission.READ_EXTERNAL_STORAGE,
Permission.WRITE_EXTERNAL_STORAGE)
.onGranted(new Action<List<String>>() {
@Override
public void onAction(List<String> permissions) {
showToast("허용된 권한 갯수 : " + permissions.size());
}
})
.onDenied(new Action<List<String>>() {
@Override
public void onAction(List<String> permissions) {
showToast("거부된 권한 갯수 : " + permissions.size());
}
})
.start();
}
public void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
// 카메라 사용시 필요한 파일생성규칙과 경로를 지정
// https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=boy1120&logNo=221125026219
public File getOutputFile() {
File mediaFile = null;
try {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyApp");
System.out.println("asd mediaStorageDir : " + mediaStorageDir);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "recorded.mp4");
System.out.println("asd mediaFile : " + mediaFile);
} catch (Exception e) {
e.printStackTrace();
}
return mediaFile;
}
public void startRecording() {
if (recorder == null) {
recorder = new MediaRecorder();
}
// MediaRecorder 설정
// 마이크로 입력을 받음
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
recorder.setOutputFile(filename);
try {
// MediaRecorder 시작
recorder.prepare();
recorder.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopRecording() {
if (recorder == null) {
return;
}
recorder.stop();
recorder.release();
recorder = null;
ContentValues values = new ContentValues(10);
values.put(MediaStore.MediaColumns.TITLE, "Recorded");
values.put(MediaStore.Audio.Media.ALBUM, "Audio Album");
values.put(MediaStore.Audio.Media.ARTIST, "Mike");
values.put(MediaStore.Audio.Media.DISPLAY_NAME, "Recorded Audio");
values.put(MediaStore.Audio.Media.IS_RINGTONE, 1);
values.put(MediaStore.Audio.Media.IS_MUSIC, 1);
values.put(MediaStore.MediaColumns.DATE_ADDED, System.currentTimeMillis() / 1000);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp4");
values.put(MediaStore.Audio.Media.DATA, filename);
// 녹음을 중지햇을때 결과물로 만들어진 녹음 파일을 미디어 앨범에 등록하기 위해서는 미디어 앨범의 내용 제공자를 이용해 새로 만들어진
// 녹음 파일의 정보를 등록, 네용 제공자에 새로운 값을 추가하기 위해 ContentValues 객체에 필요한 정보를 put 메소드로 넣은 후
// insert 메소드를 이용해 이 객체를 추가
// MediaStore.Audio.Media.DATA의 값으로 녹음 파일의 경로를 지정하면 됨
Uri audioUri = getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
if (audioUri == null) {
Log.d("SampleAudioRecorder", "Audio insert failed.");
}
}
public void startPlay() {
killMediaPlayer();
try {
player = new MediaPlayer();
player.setDataSource(filename);
player.prepare();
player.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopPlay() {
if (player != null) {
player.stop();
}
}
private void killMediaPlayer() {
if (player != null) {
try {
player.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
반응형