Android利用SeekBar实现简单音乐播放器
一.Demo简介
利用AIDL为Activity绑定服务,利用Handler机制,发送消息更新SeekBar的UI,利用计时器定时更新SeekBar的进度。实现对音乐的开始播放,到暂停,继续,以及停止播放的功能。以及实现拖动进度条播放音乐的功能。
二.AIDL接口
利用AIDL机制提供给MainActivity访问MyMusicService的方法,实现播放暂停等功能。
三.主要类代码
1.MyMusicService
package my.com.mymusicp; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.os.IBinder; import android.os.Message; import android.os.RemoteException; import android.support.annotation.Nullable; import android.util.Log; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; /** * Created by c_ljf on 16-12-26. */ public class MyMusicService extends Service { private String tag="MyMusicService"; private MediaPlayer mediaPlayer; @Override public void onCreate() { super.onCreate(); mediaPlayer = new MediaPlayer(); } @Nullable @Override public IBinder onBind(Intent intent) { return new MyMusicBinder(); } class MyMusicBinder extends IMyMusicService.Stub{ @Override public void play() throws RemoteException { playmusic(); } @Override public void pause() throws RemoteException { pausemusic(); } @Override public void stop() throws RemoteException { stopmusic(); } @Override public void continuePlay() throws RemoteException { rePlayMusic(); } @Override public void seekPlayProgress(int position) throws RemoteException { seekPlayPositiom(position); } } //播放音乐 public void playmusic(){ mediaPlayer.reset(); String url = "sdcard/Music/Fade.mp3"; Log.i(tag,url); try { mediaPlayer.setDataSource(url); mediaPlayer.prepare(); } catch (IOException e) { e.printStackTrace(); } // might take long! (for buffering, etc) mediaPlayer.start(); //更新播放进度条 seekPlayProgress(); } public void pausemusic(){ mediaPlayer.pause(); Log.i(tag,"暂停播放"); } public void stopmusic(){ mediaPlayer.reset(); Log.i(tag,"停止播放"); mediaPlayer.stop(); } @Override public void onDestroy() { super.onDestroy(); } public void seekPlayPositiom(int positon){ Log.i(tag,"设置播放位置"); mediaPlayer.seekTo(positon); } public void seekPlayProgress(){ /*1.获取当前歌曲的总时长*/ final int duration=mediaPlayer.getDuration(); //计时器对象 final Timer timer=new Timer(); final TimerTask task=new TimerTask() { @Override public void run() { //开启线程定时获取当前播放进度 int currentposition=mediaPlayer.getCurrentPosition(); //利用message给主线程发消息更新seekbar进度 Message ms=Message.obtain(); Bundle bundle=new Bundle(); bundle.putInt("duration",duration); Log.i(tag,"歌曲总长度"+duration); bundle.putInt("currentposition",currentposition); Log.i(tag,"当前长度"+currentposition); //设置发送的消息内容 ms.setData(bundle); //发送消息 MainActivity.handler.sendMessage(ms); } }; timer.schedule(task,300,500); //当播放结束时停止播放 mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { Log.i(tag,"取消计时任务"); timer.cancel(); task.cancel(); } }); } public void rePlayMusic() { Log.i(tag, "继续播放音乐"); mediaPlayer.start(); } }
2.Mainactivity
package my.com.mymusicp; import android.Manifest; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.RemoteException; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.SeekBar; public class MainActivity extends AppCompatActivity { private IMyMusicService iMyMusicService; private static SeekBar seekBar; private Button btpause_play; private boolean b=true;//判断暂停和继续播放 public static Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { //处理消息 Bundle bundle=msg.getData(); //获取歌曲长度和当前播放位置,并设置到进度条上 int duration=bundle.getInt("duration"); int currentposition=bundle.getInt("currentposition"); seekBar.setMax(duration); seekBar.setProgress(currentposition); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); verifyStoragePermissions(MainActivity.this); //获取播放暂停按钮 btpause_play=(Button) findViewById(R.id.bt_pause); Intent intent=new Intent(MainActivity.this,MyMusicService.class); bindService(intent,new MyConn(),BIND_AUTO_CREATE); seekBar=(SeekBar) findViewById(R.id.seekBar); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { try { iMyMusicService.seekPlayProgress(seekBar.getProgress()); } catch (RemoteException e) { e.printStackTrace(); } } }); } //定义服务连接类 class MyConn implements ServiceConnection{ @Override public void onServiceConnected(ComponentName name, IBinder service) { iMyMusicService=IMyMusicService.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName name) { } } public void play(View v){ try { iMyMusicService.play(); } catch (RemoteException e) { e.printStackTrace(); } } public void pause(View v){ try { if(b) { iMyMusicService.pause(); b=false; btpause_play.setText("继续播放"); } else{ b=true; iMyMusicService.continuePlay(); btpause_play.setText("暂停播放"); } } catch (RemoteException e) { e.printStackTrace(); } } public void stop(View v){ try { iMyMusicService.stop(); } catch (RemoteException e) { e.printStackTrace(); } } // Storage Permissions private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, }; /** * Checks if the app has permission to write to device storage * * If the app does not has permission then the user will be prompted to grant permissions * * @param activity */ public static void verifyStoragePermissions(Activity activity) { // Check if we have write permission int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { // We don't have permission so prompt the user ActivityCompat.requestPermissions( activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE ); } } }
四.布局文件
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="my.com.mymusicp.MainActivity"> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:id="@+id/linearLayout"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="开始播放" android:onClick="play" android:id="@+id/bt_start"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="暂停播放" android:layout_weight="1" android:onClick="pause" android:id="@+id/bt_pause"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="停止播放" android:onClick="stop" android:id="@+id/bt_stop"/> </LinearLayout> <SeekBar android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/seekBar" android:layout_below="@+id/linearLayout" android:layout_alignParentLeft="true" android:layout_alignParentStart="true"/> </RelativeLayout>
五.注册服务
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="my.com.mymusicp"> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" 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> <service android:name=".MyMusicService"/> </application> </manifest>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)