음악 파일 재생하기
activity_main.xml
<?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>
최상위 레이아웃을 LinearLyout으로 바꾸고 orientation 속성 값을 vertical로 설정한 후 네 개의 버튼을 추가합니다. 버튼의 text속성은 '재생','중지','일시정지','재시작'으로 변경합니다 레이아웃에 추가한 네 개의 버튼 중에서 첫 번쨰 버튼을 누르면 오디오 재생을 위한 3단계를 거치면서 음악 파일을 재생합니다.두 번쨰 버튼은 중지, 세 번쨰 버튼은 일시정지 네 번쨰 버튼은 재시작 기능을 수행하도록 수정합니다
MainActivity.java
package org.techtown.audio.player;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
public static final String AUDIO_URL = "http://sites.google.com/site/ubiaccessmobile/sample_audio.amr";
MediaPlayer mediaPlayer;
int position = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
playAudio(AUDIO_URL);
Toast.makeText(getApplicationContext(),"음악 파일 재생 시작됨.", Toast.LENGTH_LONG).show();
}
});
Button button2 = findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mediaPlayer != null) {
mediaPlayer.stop();
Toast.makeText(getApplicationContext(),"음악 파일 재생 중지됨.",
Toast.LENGTH_LONG).show();
}
}
});
Button button3 = findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mediaPlayer != null) {
position = mediaPlayer.getCurrentPosition();
mediaPlayer.pause();
Toast.makeText(getApplicationContext(),"음악 파일 재생 일시정지됨.",
Toast.LENGTH_LONG).show();
}
}
});
Button button4 = findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
mediaPlayer.start();
mediaPlayer.seekTo(position);
Toast.makeText(getApplicationContext(),"음악 파일 재생 재시작됨.",
Toast.LENGTH_LONG).show();
}
}
});
}
private void playAudio(String url) {
killMediaPlayer();
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.start();
} catch(Exception e) {
e.printStackTrace();
}
}
protected void onDestroy() {
super.onDestroy();
killMediaPlayer();
}
private void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.release();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
MediaPlayer객체를 이용해 음악을 재생하는 playAudio 메서드의 구조를 보면 killMediaPlayer메서드를 호출한 후 차례로 setDataSource,prepare,start메서드를 호출하고 있습니다.killMediaPlayer메서드는 미디어플레이어 객체가 이미 리소스를 사용하고 있을 경우에 release메서드를 호출하여 리소스를 해제하는 역할을 합니다.리소스를 해제를 해야되는 이유는 미디어플레이어를 앱에서 재사용하면 기존에 사용하던 리소스를 먼저 해제해야 하기 떄문입니다재생을 중지하고 다시 시작하기 위해서는 중지한 지점에서 위피를 알아야 하므로 [일시정지]버튼을 눌렀을 떄 getCurrentPosition메서드를 이용해 현 지점의 위치를 알아 오고 [재시작]버튼을 눌렸을 때는 seekTo메서드로 중지했을 떄는 지점에서부터 재생하도록 만듭니다.인터넷에서 파일을 받아 오기 떄문에 INTERNET권한이 필요합니다.AndroidManifest.xml파일을 열고 다음과 같이 INTERNET권한을 추가합니다<application>태그에 속성을 하나 더 추가합니다.