使用 MediaPlayer 類在 Android 應用中實現基本的音訊播放器
本示例演示瞭如何在 Android 應用中建立 MediaPlayer 類以實現基本的音訊播放器。
步驟 1 - 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。
步驟 2 - 將以下程式碼新增到 res/layout/activity_main.xml。
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://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="http://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 Studio 執行應用程式,請開啟專案的某個活動檔案,然後單擊工具欄中的執行 圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 -
點選 此處 下載專案程式碼。
廣告