之前看到網頁版的網易音樂播放控件, 正好在一個開源學習項目中需要簡單的音樂播放功能。所以想是不是可以封裝一個音樂播放控件,提供一個類似網易播放控件的默認界面,而且提供更換界面的功能。使用時,只需要去設計界面, 而不用再去管音樂播放的邏輯,所以就實現了一個簡單的音樂播放控件。
音樂播放控件(MiniMusicView) 使用方法:
1.使用默認的界面
(1) 在你的布局中加入 MiniMusicView
<com.hrb.library.MiniMusicView android:id="@+id/mmv_music" app:isLoadLayout="true" android:layout_width="match_parent" android:layout_height="match_parent" />
(2) 設置音樂地址并播放音樂
mMusicView = (MiniMusicView) findViewById(R.id.mmv_music); mMusicView.setTitleText("music name"); mMusicView.setAuthor("singer name"); mMusicView.startPlayMusic("music url"); // Or through the new way to create view object // mMusicView = new MiniMusicView(this); // mMusicView.initDefaultView(); // mMusicView.setTitleText("music name"); // mMusicView.startPlayMusic("music url");
(3) 停止音樂播放
@Override protected void onDestroy() { mMusicView.stopPlayMusic(); super.onDestroy(); }
效果圖如下:
2.使用自定義布局
(1) 在你的布局中加入 MiniMusicView
<com.hrb.library.MiniMusicView android:id="@+id/mmv_music" android:layout_width="match_parent" android:layout_height="match_parent" />
(2) 設置自定義布局,設置音樂地址,播放音樂
mMusicView = (MiniMusicView) findViewById(R.id.mmv_music); View view = View.inflate(CustomActivity.this, R.layout.layout_custom_music, null); TextView title.setText("music name"); mMusicView.addView(view); mMusicView.startPlayMusic("music url"); // Or through the new way to create view object // mMusicView = new MiniMusicView(this); // mMusicView.addView(view); // mMusicView.startPlayMusic("music url");
效果圖如下:
(3) MiniMusicView 還提供音樂狀態的回調監聽接口
mMusicView.setOnMusicStateListener(new MiniMusicView.OnMusicStateListener() { @Override public void onPrepared(int duration) { Log.i(TAG, "start prepare play music"); } @Override public void onError() { Log.i(TAG, "start play music error"); } @Override public void onInfo(int what, int extra) { Log.i(TAG, "start play_mini_music music info"); } @Override public void onMusicPlayComplete() { Log.i(TAG, "start play music completed"); } @Override public void onSeekComplete() { Log.i(TAG, "seek play music completed"); } @Override public void onProgressUpdate(int duration, int currentPos) { Log.i(TAG, "play music progress update"); } @Override public void onHeadsetPullOut() { Log.i(TAG, "headset pull out"); } });
你可以在相應的監聽中去完成需要的行為, 例如要實現當耳機拔出,實現音樂播放停止, 可以在onHeadsetPullOut()接口中調用mMusicView.pausePlayMusic() 暫停音樂播放。
另外,MiniMusicView如何在工程中使用和源碼可以從這里獲取,大家可以根據需要進行修改, 如果使用中有bug請留言,不勝感激.
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答