이 예는 Android 앱에서 기본 오디오 플레이어를 구현하기 위해 Mediaplayer 클래스를 생성하는 방법을 보여줍니다.
1단계 − Android Studio에서 새 프로젝트를 생성하고 파일 ⇒ 새 프로젝트로 이동하여 필요한 모든 세부 정보를 입력하여 새 프로젝트를 생성합니다.
2단계 − res/layout/activity_main.xml에 다음 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="10dp" android:paddingRight="10dp"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Now Playing: " android:layout_marginTop="30dp" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/txtSongName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textView" android:layout_toEndOf="@+id/textView" /> <ImageButton android:id="@+id/btnBackward" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_marginBottom="44dp" android:layout_marginLeft="20dp" android:src="@drawable/ic_back" /> <ImageButton android:id="@+id/btnPlay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/btnBackward" android:layout_marginLeft="20dp" android:layout_toRightOf="@+id/btnBackward" android:src="@drawable/ic_play" /> <ImageButton android:id="@+id/btnPause" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/btnPlay" android:layout_marginLeft="20dp" android:layout_toRightOf="@+id/btnPlay" android:src="@drawable/ic_pause" /> <ImageButton android:id="@+id/btnForward" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/btnPause" android:layout_marginLeft="20dp" android:layout_toRightOf="@+id/btnPause" android:contentDescription="@+id/imageButton3" android:src="@drawable/ic_forward" /> <TextView android:id="@+id/txtStartTime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/seekBar" android:text="0 min, 0 sec" /> <SeekBar android:id="@+id/seekBar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@+id/btnBackward" android:layout_toLeftOf="@+id/txtSongTime" android:layout_toRightOf="@+id/txtStartTime" /> <TextView android:id="@+id/txtSongTime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@+id/btnForward" android:layout_alignTop="@+id/seekBar" android:text="0 min, 0 sec " /> </RelativeLayout>
3단계 − src/MainActivity.java
에 다음 코드 추가import android.media.MediaPlayer; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.util.concurrent.TimeUnit; public class MainActivity extends AppCompatActivity { private ImageButton forwardBtn, backwardBtn, pauseBtn, playBtn; private MediaPlayer mediaPlayer; private TextView songName, startTime, songTime; private SeekBar songProgress; private static int onTime =0, playTime =0, endTime =0, forwardTime = 5000, backwardTime = 5000; private Handler handler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); backwardBtn = findViewById(R.id.btnBackward); forwardBtn = findViewById(R.id.btnForward); playBtn = findViewById(R.id.btnPlay); pauseBtn = findViewById(R.id.btnPause); songName = findViewById(R.id.txtSongName); startTime = findViewById(R.id.txtStartTime); songTime = findViewById(R.id.txtSongTime); songName.setText("Bohemian_Rhapsody"); mediaPlayer = MediaPlayer.create(this, R.raw.bohemian_rhapsody); songProgress = findViewById(R.id.seekBar); songProgress.setClickable(false); pauseBtn.setEnabled(false); playBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Playing Audio", Toast.LENGTH_SHORT).show(); mediaPlayer.start(); endTime = mediaPlayer.getDuration(); playTime = mediaPlayer.getCurrentPosition(); if (onTime == 0) { songProgress.setMax(endTime); onTime = 1; } songTime.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(endTime), TimeUnit.MILLISECONDS.toSeconds(endTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(endTime)))); startTime.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(playTime), TimeUnit.MILLISECONDS.toSeconds(playTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(playTime)))); songProgress.setProgress(playTime); handler.postDelayed(UpdateSongTime, 100); pauseBtn.setEnabled(true); playBtn.setEnabled(false); } }); pauseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mediaPlayer.pause(); pauseBtn.setEnabled(false); playBtn.setEnabled(true); Toast.makeText(getApplicationContext(), "Pausing Audio", Toast.LENGTH_SHORT).show(); } }); forwardBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if ((playTime + forwardTime) <= endTime) { playTime = playTime + forwardTime; mediaPlayer.seekTo(playTime); } else { Toast.makeText(getApplicationContext(), "Cannot jump forward 5 seconds", Toast.LENGTH_SHORT).show(); } if (!playBtn.isEnabled()) { playBtn.setEnabled(true); } } }); backwardBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if ((playTime - backwardTime) > 0) { playTime = playTime - backwardTime; mediaPlayer.seekTo(playTime); } else { Toast.makeText(getApplicationContext(), "Cannot jump backward 5 seconds", Toast.LENGTH_SHORT).show(); } if (!playBtn.isEnabled()) { playBtn.setEnabled(true); } } }); } private Runnable UpdateSongTime = new Runnable() { @Override public void run() { playTime = mediaPlayer.getCurrentPosition(); startTime.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(playTime), TimeUnit.MILLISECONDS.toSeconds(playTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(playTime))) ); songProgress.setProgress(playTime); handler.postDelayed(this, 100); } }; }
4단계 - androidManifest.xml에 다음 코드 추가
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample"> <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>
응용 프로그램을 실행해 보겠습니다. 실제 Android 모바일 장치를 컴퓨터에 연결했다고 가정합니다. Android 스튜디오에서 앱을 실행하려면 프로젝트의 활동 파일 중 하나를 열고 도구 모음에서 실행 아이콘을 클릭합니다. 모바일 장치를 옵션으로 선택한 다음 기본 화면을 표시할 모바일 장치를 확인하십시오 –