首页 > 系统 > Android > 正文

Android实现简单音乐播放控件

2019-10-22 18:12:19
字体:
来源:转载
供稿:网友

之前看到网页版的网易音乐播放控件, 正好在一个开源学习项目中需要简单的音乐播放功能。所以想是不是可以封装一个音乐播放控件,提供一个类似网易播放控件的默认界面,而且提供更换界面的功能。使用时,只需要去设计界面, 而不用再去管音乐播放的逻辑,所以就实现了一个简单的音乐播放控件。

音乐播放控件(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(); }

效果图如下:

Android,音乐播放控件,播放控件

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");

效果图如下:

Android,音乐播放控件,播放控件

(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武林网。


注:相关教程知识阅读请移步到Android开发频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表