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



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
<?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">
    <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

인터넷 권한 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?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.INTERNET" />
 
    <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. MainActivity.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
package com.tistory.qlyh8.practice;
 
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
 
import java.io.IOException;
 
 
public class MainActivity extends AppCompatActivity {
 
    // 음악 파일 위치 지정
    // 1. 인터넷에 있는 파일일 때
    String url = "http://sites.google.com/site/ubiaccessmobile/sample_audio.amr";
    // 2. 프로젝트 파일에 포함된 음악 파일일 때 (프로젝트의 res/raw 폴더에 a.mp3 라는 이름의 음악 파일)
    // MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.a);
    // 3. 단말 SD 카드에 넣은 음악 파일일 때
    // String filepath = "/sdcard/a.mp3";
    // MediaPlayer mediaPlayer = new MediaPlayer();
    // mediaPlayer.setDataSource(filepath);
    MediaPlayer mediaPlayer;
    int position = 0;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        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(url); // 음악 파일 위치 지정
                    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();
                }
            }
        });
    }
}
cs



5. 참고

- MediaPlayer LifeCycle: https://developer.android.com/reference/android/media/MediaPlayer

'Android' 카테고리의 다른 글

음성 녹음하기  (0) 2018.08.23
동영상 재생하기  (0) 2018.08.23
카메라 미리 보여주기  (0) 2018.08.23
사진 찍어 보여주기  (0) 2018.08.23
인터넷 연결상태 확인하기  (0) 2018.08.19

+ Recent posts