안녕, 세상!

13. 멀티미디어 본문

It공부/안드로이드

13. 멀티미디어

dev_Lumin 2020. 8. 30. 14:33

(1) 오디오

멀티미디어를 동작시키기 위해 제공되는 MediaPlayer클래스는 음악과 동영상을 재생해주는 기능을 합니다.

MediaPlayer의 play(), pause(), stop() 메소드는 각각 음악을 시작, 일시정지, 정지하는 기능을 합니다.

MediaPlayer을 활용한 예제를 보기 전에 다양한 리소스 파일이 저장되는 위치를 정리하겠습니다.

 

리소스 파일과 저장 폴더

리소스 폴더 저장 파일
그림 파일 /res/drawable *.png, *jpg, *xml
메뉴 파일 /res/menu *.xml
기타 XML 파일 /res/xml *.xml
raw 파일(음악, 동영상, 텍스트 파일) /res/raw *.mp3, *mp4, *txt
레이아웃 파일 /res/layout *.xml
문자열(String) /res/values string.xml
문자 배열(String Array) /res/values arrays.xml
색상값 /res/values array.xml
스타일 /res/values styles.xml
테마 /res/values themes.xml

 

다음은 MediaPlayer을 이용한 MP3 플레이어의 예제입니다.

 

우선 AVD를 실행시킨 상태로 AVD의 Device File Explorer의 sdcard 폴더에 음악파일을 upload 시킵니다.

저는 무 저작권 노래를 다운로드하여서 업로드했습니다. (castle, maze, wave)

 

 

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
50
51
52
53
<?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">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="6" >
        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/listViewMP3" />
    </LinearLayout>
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="horizontal">
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/btnplay"
            android:text="재생" />
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:id="@+id/btnstop"
            android:text="중지" />
    </LinearLayout>
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv"
            android:text="실행중인 음악: " />
        <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/pb"
            android:visibility="invisible" />
    </LinearLayout>
</LinearLayout>
cs

 

 

AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application

    android:requestLegacyExternalStrage="true"

 

 

 

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
83
84
85
86
87
88
89
90
91
92
93
94
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
 
public class MainActivity extends AppCompatActivity {
    ListView listviewmp3;
    Button btnplay, btnstop;
    TextView tvmp3;
    ProgressBar pbmp3;
 
    ArrayList<String> mp3List;
    String selectedMP3;
 
    String mp3Path = Environment.getExternalStorageDirectory().getPath()+"/";
    MediaPlayer mPlayer;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("간단 MP3 플레이어");
        ActivityCompat.requestPermissions(thisnew String[] {android.Manifest.permission.WRITE_EXTERNAL_STORAGE},MODE_PRIVATE);
        // 권한 요청 메시지
 
        mp3List= new ArrayList<String>();
 
        File[] listFiles = new File(mp3Path).listFiles();
        String fileName, extName;
        for(File file : listFiles){
            fileName = file.getName();              // 파일 이름 추출
            extName = fileName.substring(fileName.length()-3);  // 확장자명 추출
            if(extName.equals((String"mp3")) //확장자명이 mp3이면
                mp3List.add(fileName);  // mp3List에 해당 파일명을 추가함
        }
 
        listviewmp3 = (ListView) findViewById(R.id.listViewMP3);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice,mp3List);
        listviewmp3.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        listviewmp3.setAdapter(adapter);
        listviewmp3.setItemChecked(0,true);
 
        listviewmp3.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){
                selectedMP3 = mp3List.get(arg2);
            }
        });
        selectedMP3 = mp3List.get(0); // 처음실행될 때 선택된 MP3파일을 리스트뷰의 첫 번째 MP3파일로 설정함
 
        btnplay = (Button) findViewById(R.id.btnplay);
        btnstop = (Button) findViewById(R.id.btnstop);
        tvmp3 = (TextView) findViewById(R.id.tv);
        pbmp3 = (ProgressBar) findViewById(R.id.pb);
 
        btnplay.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                try{
                    mPlayer= new MediaPlayer();
                    mPlayer.setDataSource(mp3Path + selectedMP3);
                    mPlayer.prepare();
                    mPlayer.start();
                    btnplay.setClickable(false);
                    btnstop.setClickable(true);
                    tvmp3.setText("실행중인 음악: "+selectedMP3);
                    pbmp3.setVisibility(View.VISIBLE);
                }catch(IOException e){
                }
            }
        });
 
        btnstop.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                mPlayer.stop();
                mPlayer.reset();
                btnplay.setClickable(true);
                btnstop.setClickable(false);
                tvmp3.setText("실행중인 음악: ");
                pbmp3.setVisibility(View.INVISIBLE);
            }
        });
        btnstop.setClickable(false); // MediaPlayer가 시작되지 않은 상태에서 <중지>를 클릭 못하게 설정
    }
}
cs

다음과 같이 화면이 나옵니다.

 

재생을 누르면 재생되는 음악의 제목이 textview에 나타나며 음악이 나옵니다.

중지를 누르면 음악이 중지됩니다.

 

 

 

 

(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
<?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">
    <ProgressBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/progressbar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:max="100"
        android:progress="30" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btninc"
        android:text="10씩 증가" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btndec"
        android:text="10씩 감소" />
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tvseek" />
    <SeekBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/seekbar"/>
</LinearLayout>
cs

 

 

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
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        final ProgressBar pb1;
        Button btninc, btndec;
        pb1=(ProgressBar) findViewById(R.id.progressbar1);
        btninc = (Button) findViewById(R.id.btninc);
        btndec = (Button) findViewById(R.id.btndec);
 
        btninc.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                pb1.incrementProgressBy(10); //10만큼 증가
            }
        });
 
        btndec.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                pb1.incrementProgressBy(-10); //-10만큼 감소
            }
        });
 
        final TextView tvSeek = (TextView) findViewById(R.id.tvseek);
        SeekBar seekBar1 = (SeekBar) findViewById(R.id.seekbar);
 
        seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tvSeek.setText("진행률 : "+progress+" %");
            }
 
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
 
            }
 
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
 
            }
        });
    }
}
cs

'10씩 증가/감소' 버튼을 누르면 프로그레스바가 10씩 변화를 하고 SeekBar을 마우스로 직접 조절을 하면 진행률의 변화를 확인할 수 있습니다.

 

 

 

 

② 쓰레드의 기본

쓰레드(thread)는 여러 작업을 동시에 수행하기 위해 사용하는 개념으로 멀티쓰레트(Multi-Thread)라고도 부릅니다.

쓰레드는 프로세스(전체 프로그램 동작) 안에서 동작하는 가장 단위입니다.

 

일반적인 함수는 하나의 작업이 끝나야 다음 작업이 진행되지만, 쓰레드는 하나의 작업이 끝나기 전에 다른 작업을 동시에 진행시킬 수 있습니다.

 

쓰레드의 java 형식은 다음과 같습니다.

 

new Thread() {
    public void run() {

        // 이 곳에 작업을 코딩

    }

}.start();

 

특정 프로세스를 동시에 진행시키는 예제는 다음과 같습니다.

전체 길이가 100인 프로그래스 바 두 개가 있습니다.

하나는 10 정도에 위치하고 한 번에 건너뛰는 폭이 2입니다.

다른 하나는 30 정도에 위치하고 한 번에 건너뛰는 폭이 1입니다.

이 두 가지 프로그레스바에 대한 동작을 동시에 수행하는 것을 눈으로 확인하기 위해서 쓰레드를 사용하겠습니다.

 

 

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
<?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">
   <SeekBar
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/sb1"
       android:max="100"
       android:progress="10" />
    <SeekBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/sb2"
        android:max="100"
        android:progress="30" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button1"
        android:text="쓰레드 시작" />
</LinearLayout>
cs

 

 

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
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import androidx.appcompat.app.AppCompatActivity;
 
public class MainActivity extends AppCompatActivity {
    ProgressBar pb1, pb2;
    Button btn;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        pb1 = (ProgressBar) findViewById(R.id.sb1);
        pb2 = (ProgressBar) findViewById(R.id.sb2);
        // 시크바는 프로그레스바의 상속을 받으므로 모든 속성을 동일하게 사용할 수 있음
// 시크바가 더 보기 편해서 xml에서 시크바틀을 사용
        btn = (Button) findViewById(R.id.button1);
 
        btn.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                new Thread() {  // 첫번째 쓰레드
                    public void run() {
                        for(int i=pb1.getProgress(); i<100; i=i+2) {
                            pb1.setProgress(pb1.getProgress()+2);
                            SystemClock.sleep(100);
                        }
                    }
                }.start();
 
                new Thread() {   // 두번째 쓰레드
                    public void run() {
                        for(int i=pb2.getProgress(); i<100; i++) {
                            pb2.setProgress(pb2.getProgress()+1);
                            SystemClock.sleep(100);
                        }
                    }
                }.start();
            }
        });
    }
}
cs

'쓰레드 시작'버튼을 누르면 둘이 동시에 작업을 수행하며 첫번째 프로그레스바가 먼저 도착하는 것을 확인할 수 있습니다.

 

 

 

 

③ UI 쓰레드

UI(User Interface) 쓰레드는 화면의 위젯을 변경할 때 사용합니다.

일반적인 쓰레드는 쓰레드 안에서 필요한 내용을 계산하는 것만 가능하며 화면의 다른 위젯을 변경할 수 없습니다.

쓰레드가 UI쓰레드를 사용하지 않고 위젯을 변경하려고 하면 오류가 납니다.

이러한 문제를 해결하기 위해서 위젯을 변경하는 부분을 runOnUiThread() 안에 넣어야 합니다.

형식은 다음과 같습니다.

 

runOnUiThread(new Runnable() {

    public void run() {

        ....위젯을 변경하는 코드는 이곳에 넣으면 됨

    }

}

 

일반 쓰레드가 위젯을 변경하려고 하면 오류가 난다고 말했습니다.

그렇다면 위의 예제에서 시크바 위젯을 변경했는데 문제없이 동작했습니다.

예외적으로 프로그레스바와 그 자식 위젯은 쓰레드 안에서 변경이 가능합니다.

하지만 프로그레스바를 변경할 때도 UI쓰레드를 사용하는 것이 더 안정적입니다.

 

다음은 위의 프로그레스바 예제에 진행률이라는 TextView를 추가해서 진행률이 숫자로 변화하는 것을 확인할 수 있는 예제입니다.

전의 예제와 코드가 크게 차이가 없습니다

 

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
<?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">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv1"
        android:text="1번 진행률: " />
   <SeekBar
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/sb1"
       android:max="100"
       android:progress="10" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv2"
        android:text="2번 진행률: " />
    <SeekBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/sb2"
        android:max="100"
        android:progress="30" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button1"
        android:text="쓰레드 시작" />
</LinearLayout>
cs

 

 

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
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
 
import androidx.appcompat.app.AppCompatActivity;
 
public class MainActivity extends AppCompatActivity {
    ProgressBar pb1, pb2;
    Button btn;
    TextView tv1,tv2;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        tv1 = (TextView) findViewById(R.id.tv1);
        tv2 = (TextView) findViewById(R.id.tv2);
        pb1 = (ProgressBar) findViewById(R.id.sb1);
        pb2 = (ProgressBar) findViewById(R.id.sb2);
        // 시크바는 프로그레스바의 상속을 받으므로 모든 속성을 동일하게 사용할 수 있음
        btn = (Button) findViewById(R.id.button1);
 
        btn.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                new Thread() {  // 첫번째 쓰레드
                    public void run() {
                        for(int i=pb1.getProgress(); i<100; i=i+2) {
                            runOnUiThread(new Runnable(){
                                public void run(){
                                    pb1.setProgress(pb1.getProgress()+2);
                                    tv1.setText("1번 진행률: "+pb1.getProgress()+"%");
                                }
                            });
                            SystemClock.sleep(100);
                        }
                    }
                }.start();
 
                new Thread() {   // 두번째 쓰레드
                    public void run() {
                        for(int i=pb2.getProgress(); i<100; i++) {
                            runOnUiThread(new Runnable(){
                                public void run(){
                                    pb2.setProgress(pb2.getProgress()+1);
                                    tv2.setText("2번 진행률: "+pb2.getProgress()+"%");
                                }
                            });
                            SystemClock.sleep(100);
                        }
                    }
                }.start();
            }
        });
    }
}
cs

 

 

④ 쓰레드 응용

맨 처음에 만든 mp3 플레이어 앱에 쓰레드를 사용해서 몇 가지 기능들을 더 추가해보겠습니다.

mp3파일의 길이만큼 SeekBar로 표기하며 시간을 표시해주는 기능을 넣어보겠습니다.

 

 

activity_main.xml

위의 코드에서 마지막 LinearLayout부분을 다음과 같이 바꿉니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv"
            android:text="실행중인 음악: " />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="진행시간: "
            android:id="@+id/tvtime" />
        <SeekBar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/pbmp3" />
    </LinearLayout>
cs

 

 

MainActivity.java

기존의 ProgressiveBar pbmp3 관련된 코드는 모두 삭제를 하고

xml파일에서 추가해준 위젯에 대한 객체를 만들고 id와 연결시켜 초기화시킵니다.

 

TextView tvtime;

SeekBar pbmp3;

tvtime = (TextView) findViewById(R.id.tvtime);

pbmp3 = (SeekBar) findViewById(R.id.pbmp3);

 

 

btnplay.setOnClickListener 부분의 76번째 줄에 다음 코드를 넣어서 음악 재생되는 동안의 프로그레스바 진행시간을 설정합니다.

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
btnplay.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                try{
                    mPlayer= new MediaPlayer();
                    mPlayer.setDataSource(mp3Path + selectedMP3);
                    mPlayer.prepare();
                    mPlayer.start();
                    btnplay.setClickable(false);
                    btnstop.setClickable(true);
                    tvmp3.setText("실행중인 음악: "+selectedMP3);
                    new Thread() {
                        SimpleDateFormat timeFormat= new SimpleDateFormat("mm:ss");
                        //진행시간을 표현하기 위해서 SimpleDateFormat객체 사용
                        public void run() {
                            if(mPlayer==nullreturn//mPlayer가 제거,중단되면 메소드 빠져나감
                            pbmp3.setMax(mPlayer.getDuration()); //해당 mp3의 파일길이를 파악해서 시크바의 최대치를 설정
                            while(mPlayer.isPlaying()) {  //mp3파일이 실행되면
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        pbmp3.setProgress(mPlayer.getCurrentPosition()); //mp3파일의 최근 위치를 계속 초기화
                                        tvtime.setText("진행시간: "+timeFormat.format(mPlayer.getCurrentPosition())); //시간을 표기
                                    }
                                });
                                SystemClock.sleep(200); //0.2초마다 진행상태 
                            }
                        }
                    }.start();
                }catch(IOException e){
                }
            }
        });
cs

 

'중지'버튼을 눌렀을 때 시크바를 원래 상태로 돌리기 위해 다음과 같이 추가해줍니다.

1
2
3
4
5
6
7
8
9
10
11
12
btnstop.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                mPlayer.stop();
                mPlayer.reset();
                btnplay.setClickable(true);
                btnstop.setClickable(false);
                tvmp3.setText("실행중인 음악: ");
                pbmp3.setProgress(0);  // 시크바를 처음으로 설정
                tvtime.setText("진행시간: ");  // 
            }
        });
        btnstop.setClickable(false); // MediaPlayer가 시작되지 않은 상태에서 <중지>를 클릭 못하게 설정
cs

 

사용자가 시크바를 직접 눌러서 해당 음원 시간으로 음원이 나오도록 다음과 같이 설정합니다.

(위의 코드 다음에 작성하면 됨)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
pbmp3.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromuser) {
                if(fromuser){ // 사용자가 시크바에 터치를 하면
                    mPlayer.seekTo(progress); // mp3파일재생을 해당 시크바의 progress부분으로 설정
                }
            }
 
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
 
            }
 
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
 
            }
        }); 
cs

 

 

결과는 다음과 같습니다.

음악의 길이에 맞게 시크바가 진행되고 진행시간도 알맞게 흘러가는 것을 확인할 수 있습니다.

또한 사용자가 직접 시크바 부분을 클릭함으로써 해당 부분의 음악으로 넘어가 재생할 수 있는 기능도 잘 됩니다.

 

 

'It공부 > 안드로이드' 카테고리의 다른 글

14. 구글지도  (0) 2020.08.31
12. 데이터 관리  (0) 2020.08.29
11. 어댑터뷰  (0) 2020.08.27
10. 액티비티와 인텐트  (0) 2020.08.26
9. 그래픽  (0) 2020.08.25
Comments