Source: https://www.edwith.org/boostcourse-android/lecture/17106/



1. 실행결과 화면

  


2. activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context="com.tistory.qlyh8.practice.MainActivity">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="30dp"
        android:gravity="center">
        <Button
            android:id="@+id/button5"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="녹음시작"/>
        <Button
            android:id="@+id/button6"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:text="녹음중지"/>
    </LinearLayout>
 
    <Button
        android:id="@+id/button1"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="재생"/>
    <Button
        android:id="@+id/button2"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="일시정지"/>
    <Button
        android:id="@+id/button3"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="다시시작"/>
    <Button
        android:id="@+id/button4"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="정지"/>
</LinearLayout>
 
cs



3. AndroidManifest.xml

녹음 권한, SD 카드 접근 권한 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tistory.qlyh8.practice">
 
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
 
    <application
        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/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>
cs



4. MainAcitivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package com.tistory.qlyh8.practice;
 
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.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
 
import java.io.File;
import java.io.IOException;
 
 
public class MainActivity extends AppCompatActivity {
 
    MediaRecorder recorder;
    String fileName;
    MediaPlayer mediaPlayer;
    int position = 0;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // SD 카드 폴더 지정
        File file = new File(Environment.getExternalStorageDirectory(), "recorded.mp4");
        fileName = file.getAbsolutePath();  // 파일 위치 가져옴
        Toast.makeText(getApplicationContext(), "파일 위치:"+fileName, Toast.LENGTH_SHORT).show();
 
        findViewById(R.id.button5).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {   // 녹음 시작
                if (recorder == null) {
                    recorder = new MediaRecorder(); // 미디어리코더 객체 생성
                }
                recorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 오디오 입력 지정(마이크)
                recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);    // 출력 형식 지정
                //마이크로 들어오는 음성데이터는 용량이 크기 때문에 압축이 필요
                recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);   // 인코딩
                recorder.setOutputFile(fileName);  // 음성 데이터를 저장할 파일 지정
                try {
                    recorder.prepare();
                    recorder.start();
                    Toast.makeText(getApplicationContext(), "녹음시작", Toast.LENGTH_SHORT).show();
                } catch (Exception e) {e.printStackTrace();}
            }
        });
 
        findViewById(R.id.button6).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {   // 녹음 중지
                if (recorder != null) {
                    recorder.stop();
                    recorder.release();
                    recorder = null;
                }
                Toast.makeText(getApplicationContext(), "녹음중지", Toast.LENGTH_SHORT).show();
            }
        });
 
        findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {  // 재생
                try {
                    if(mediaPlayer != null){    // 사용하기 전에
                        mediaPlayer.release();  // 리소스 해제
                        mediaPlayer = null;
                    }
                    mediaPlayer = new MediaPlayer();
                    mediaPlayer.setDataSource(fileName); // 음악 파일 위치 지정
                    mediaPlayer.prepare();  // 미리 준비
                    mediaPlayer.start();    // 재생
                    Toast.makeText(getApplicationContext(), "재생시작", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
 
        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {  // 일시정지
                if(mediaPlayer != null) {
                    position = mediaPlayer.getCurrentPosition();    // 어디까지 재생되었는지 알아냄
                    mediaPlayer.pause();    // 일시정지
                    Toast.makeText(getApplicationContext(), "일시정지", Toast.LENGTH_SHORT).show();
                }
            }
        });
 
        findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { // 다시시작
                if(mediaPlayer != null && !mediaPlayer.isPlaying()) {
                    mediaPlayer.seekTo(position);   // 시작되는 위치
                    mediaPlayer.start();    // 시작
                    Toast.makeText(getApplicationContext(), "다시시작", Toast.LENGTH_SHORT).show();
                }
            }
        });
 
        findViewById(R.id.button4).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { // 정지
                if(mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mediaPlayer.stop(); // 정지
                    Toast.makeText(getApplicationContext(), "정지", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
 
    // 녹음한 파일 저장
    public Uri save(){
        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, "Ton");
        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 객체를 추가할 때, 음성 파일에 대한 내용 제공자 URI 사용
        return getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
    }
}
cs



5. build.gralde (app)

targetSdkVersion을 22 로 낮추어 위험권한이 자동 부여되게 함



6. 참고

AudioRecord: https://developer.android.com/reference/android/media/AudioRecord

MediaRecorder: https://developer.android.com/guide/topics/media/mediarecorder


'Android' 카테고리의 다른 글

스레드 애니메이션 (Thread Animation)  (0) 2018.08.24
RecyclerView (리사이클러뷰)  (0) 2018.08.23
동영상 재생하기  (0) 2018.08.23
음악 재생하기  (0) 2018.08.23
카메라 미리 보여주기  (0) 2018.08.23

+ Recent posts