Android實現簡單音樂播放器(MediaPlayer)
工程內容
實現一個簡單的音樂播放器,要求功能有:
- 播放、暫停功能;
- 進度條顯示播放進度功能
- 拖動進度條改變進度功能;
- 後臺播放功能;
- 停止功能;
- 退出功能;
程式碼實現
匯入歌曲到手機SD卡的Music目錄中,這裡我匯入了4首歌曲:仙劍六裡面的《誓言成暉》、《劍客不能說》、《鏡中人》和《浪花》,也推薦大家聽喔(捂臉
然後新建一個類MusicService繼承Service,在類中定義一個MyBinder,有一個方法用於返回MusicService本身,在過載onBind()方法的時候返回
public class MusicService extends Service {
public final IBinder binder = new MyBinder();
public class MyBinder extends Binder{
MusicService getService() {
return MusicService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
}
在MusicService中,宣告一個MediaPlayer變數,進行設定歌曲路徑,這裡我選擇歌曲1作為初始化時候的歌曲
private String[] musicDir = new String[]{
Environment.getExternalStorageDirectory().getAbsolutePath() + "/Music/仙劍奇俠傳六-主題曲-《誓言成暉》.mp3",
Environment.getExternalStorageDirectory().getAbsolutePath() + "/Music/仙劍奇俠傳六-主題曲-《劍客不能說》.mp3",
Environment.getExternalStorageDirectory().getAbsolutePath () + "/Music/仙劍奇俠傳六-主題曲-《鏡中人》.mp3",
Environment.getExternalStorageDirectory().getAbsolutePath() + "/Music/仙劍奇俠傳六-主題曲-《浪花》.mp3"};
private int musicIndex = 1;
public static MediaPlayer mp = new MediaPlayer();
publicMusicService() {
try {
musicIndex = 1;
mp.setDataSource(musicDir[musicIndex]);
mp.prepare();
} catch (Exception e) {
Log.d("hint","can't get to the song");
e.printStackTrace();
}
}
設計一些歌曲播放、暫停、停止、退出相應的邏輯,此外我還設計了上一首和下一首的邏輯
publicvoidplayOrPause() {
if(mp.isPlaying()){
mp.pause();
} else {
mp.start();
}
}
publicvoidstop() {
if(mp != null) {
mp.stop();
try {
mp.prepare();
mp.seekTo(0);
} catch (Exception e) {
e.printStackTrace();
}
}
}
publicvoidnextMusic() {
if(mp != null && musicIndex < 3) {
mp.stop();
try {
mp.reset();
mp.setDataSource(musicDir[musicIndex+1]);
musicIndex++;
mp.prepare();
mp.seekTo(0);
mp.start();
} catch (Exception e) {
Log.d("hint", "can't jump next music");
e.printStackTrace();
}
}
}
publicvoidpreMusic() {
if(mp != null && musicIndex > 0) {
mp.stop();
try {
mp.reset();
mp.setDataSource(musicDir[musicIndex-1]);
musicIndex--;
mp.prepare();
mp.seekTo(0);
mp.start();
} catch (Exception e) {
Log.d("hint", "can't jump pre music");
e.printStackTrace();
}
}
}
註冊MusicService並賦予許可權,允許讀取外部儲存空間
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<service android:name="com.wsine.west.exp5_AfterClass.MusicService" android:exported="true"></service>
在MainAcitvity中宣告ServiceConnection,呼叫bindService保持與MusicService通訊,通過intent的事件進行通訊,在onCreate()函式中繫結Service
private ServiceConnection sc = new ServiceConnection() {
@Override
publicvoidonServiceConnected(ComponentName componentName, IBinder iBinder) {
musicService = ((MusicService.MyBinder)iBinder).getService();
}
@Override
publicvoidonServiceDisconnected(ComponentName componentName) {
musicService = null;
}
};
privatevoidbindServiceConnection() {
Intent intent = new Intent(MainActivity.this, MusicService.class);
startService(intent);
bindService(intent, sc, this.BIND_AUTO_CREATE);
}
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("hint", "ready to new MusicService");
musicService = new MusicService();
Log.d("hint", "finish to new MusicService");
bindServiceConnection();
seekBar = (SeekBar)this.findViewById(R.id.MusicSeekBar);
seekBar.setProgress(musicService.mp.getCurrentPosition());
seekBar.setMax(musicService.mp.getDuration());
musicStatus = (TextView)this.findViewById(R.id.MusicStatus);
musicTime = (TextView)this.findViewById(R.id.MusicTime);
btnPlayOrPause = (Button)this.findViewById(R.id.BtnPlayorPause);
Log.d("hint", Environment.getExternalStorageDirectory().getAbsolutePath()+"/You.mp3");
}
bindService函式回撥onSerciceConnented函式,通過MusiceService函式下的onBind()方法獲得binder物件並實現繫結
通過Handle實時更新UI,這裡主要使用了post方法並在Runnable中呼叫postDelay方法實現實時更新UI,Handle.post方法在onResume()中呼叫,使得程式剛開始時和重新進入應用時能夠更新UI
在Runnable中更新SeekBar的狀態,並設定SeekBar滑動條的響應函式,使歌曲跳動到指定位置
public android.os.Handler handler = new android.os.Handler();
public Runnable runnable = new Runnable() {
@Override
publicvoidrun() {
if(musicService.mp.isPlaying()) {
musicStatus.setText(getResources().getString(R.string.playing));
btnPlayOrPause.setText(getResources().getString(R.string.pause).toUpperCase());
} else {
musicStatus.setText(getResources().getString(R.string.pause));
btnPlayOrPause.setText(getResources().getString(R.string.play).toUpperCase());
}
musicTime.setText(time.format(musicService.mp.getCurrentPosition()) + "/"
+ time.format(musicService.mp.getDuration()));
seekBar.setProgress(musicService.mp.getCurrentPosition());
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
publicvoidonProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
musicService.mp.seekTo(seekBar.getProgress());
}
}
@Override
publicvoidonStartTrackingTouch(SeekBar seekBar) {
}
@Override
publicvoidonStopTrackingTouch(SeekBar seekBar) {
}
});
handler.postDelayed(runnable, 100);
}
};
@Override
protectedvoidonResume() {
if(musicService.mp.isPlaying()) {
musicStatus.setText(getResources().getString(R.string.playing));
} else {
musicStatus.setText(getResources().getString(R.string.pause));
}
seekBar.setProgress(musicService.mp.getCurrentPosition());
seekBar.setMax(musicService.mp.getDuration());
handler.post(runnable);
super.onResume();
Log.d("hint", "handler post runnable");
}
給每個按鈕設定響應函式,在onDestroy()中新增解除繫結,避免記憶體洩漏
publicvoidonClick(View view) {
switch (view.getId()) {
case R.id.BtnPlayorPause:
musicService.playOrPause();
break;
case R.id.BtnStop:
musicService.stop();
seekBar.setProgress(0);
break;
case R.id.BtnQuit:
handler.removeCallbacks(runnable);
unbindService(sc);
try {
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
break;
case R.id.btnPre:
musicService.preMusic();
break;
case R.id.btnNext:
musicService.nextMusic();
break;
default:
break;
}
}
@Override
publicvoidonDestroy() {
unbindService(sc);
super.onDestroy();
}
在Button中賦予onClick屬性指向介面函式
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/BtnPlayorPause" android:text="@string/btnPlayorPause" android:onClick="onClick"/>
效果圖
開啟介面->播放一會兒進度條實時變化->拖動進度條->點選暫停->點選Stop->點選下一首(歌曲時間變化)->點選上一首->點選退出
一些總結
- 讀取SD卡記憶體的時候,應該使用android.os.Environment庫中的getExternalStorageDirectory()方法,然而並不能生效。應該再使用getAbsolutePath()獲取絕對路徑後讀取音樂才生效。
- 切換歌曲的時候try塊不能正確執行。檢查過後,也是執行了stop()函式後再重新setDataSource()來切換歌曲的,但是沒有效果。查閱資料後,發現setDataSource()之前需要呼叫reSet()方法,才可以重新設定歌曲
瞭解Service中startService(service)和bindService(service, conn, flags)兩種模式的執行方法特點及其生命週期,還有為什麼這次要一起用
startService方法是讓Service啟動,讓Service進入後臺running狀態;但是這種方法,service與使用者是不能互動的,更準確的說法是,service與使用者不能進行直接的互動。
因此需要使用bindService方法繫結Service服務,bindService返回一個binder介面例項,使用者就可以通過該例項與Service進行互動。
Service的生命週期簡單到不能再簡單了,一條流水線表達了整個生命週期。
service的活動生命週期是在onStart()之後,這個方法會處理通過startServices()方法傳遞來的Intent物件。音樂service可以通過開打intent物件來找到要播放的音樂,然後開始後臺播放。注: service停止時沒有相應的回撥方法,即沒有onStop()方法,只有onDestroy()銷燬方法。
onCreate()方法和onDestroy()方法是針對所有的services,無論它們是否啟動,通過Context.startService()和Context.bindService()方法都可以訪問執行。然而,只有通過startService()方法啟動service服務時才會呼叫onStart()方法。
圖片來自網路,忘記出處了
簡述如何使用Handler實時更新UI
方法一:
Handle的post方法,在post的Runable的run方法中,使用postDelay方法再次post該Runable物件,在Runable中更新UI,達到實時更新UI的目的
方法二:
多開一個執行緒,執行緒寫一個持續迴圈,每次進入迴圈內即post一次Runable,然後休眠1000ms,亦可做到實時更新UI
工程下載
傳送門:下載