title: 安卓学习03 date: 2020-02-03 20:28:30 tags:
今日学习了mediaplayer的简单封装使用以及引导页。
<!--more -->
1、mediaplayer的封装
package com.example.framework.manager; ? import android.content.res.AssetFileDescriptor; import android.media.MediaPlayer; import android.os.Build; import android.os.Handler; import android.os.Message; ? import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; ? import com.example.framework.utils.LogUtils; ? import java.io.IOException; ? public class MediaPlayerManager { ? //播放 public static final int MEDIA_STATUS_PLAY = 0; //暂停 public static final int MEDIA_STATUS_PAUSE = 1; //停止 public static final int MEDIA_STATUS_STOP = 2; //当前状态 public static int MEDIA_STATUS = MEDIA_STATUS_STOP; ? public static final int H_PROGRESS = 1000; ? private MediaPlayer mediaPlayer; private OnMusicProgressListener musicProgressListener; private Handler handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage( Message msg) { switch (msg.what){ case H_PROGRESS: if (musicProgressListener != null){ int currentPosition = getCurrentPosition(); int p = (int) (((float)currentPosition)/((float)getDuration()) * 100); musicProgressListener.OnProgress(currentPosition,p); handler.sendEmptyMessageDelayed(H_PROGRESS,1000); } break; } return false; } }); ? public MediaPlayerManager() { mediaPlayer = new MediaPlayer(); } ? @RequiresApi(api = Build.VERSION_CODES.N) public void startPlay(AssetFileDescriptor path){ try { mediaPlayer.reset(); mediaPlayer.setDataSource(path); mediaPlayer.prepare(); mediaPlayer.start(); MEDIA_STATUS = MEDIA_STATUS_PLAY; handler.sendEmptyMessage(H_PROGRESS); } catch (IOException e) { LogUtils.e(e.toString()); e.printStackTrace(); } } ? //暂停播放 public void pausePlay(){ if (mediaPlayer.isPlaying()){ mediaPlayer.pause(); MEDIA_STATUS = MEDIA_STATUS_PAUSE; handler.removeMessages(H_PROGRESS); } } ? //继续播放 public void continuePlay(){ mediaPlayer.start(); MEDIA_STATUS = MEDIA_STATUS_PLAY; handler.sendEmptyMessage(H_PROGRESS); } ? //停止播放 public void stopPlay(){ mediaPlayer.stop(); MEDIA_STATUS = MEDIA_STATUS_STOP; handler.removeMessages(H_PROGRESS); } ? //获取当前位置 public int getCurrentPosition(){ return mediaPlayer.getCurrentPosition(); } ? //获取音乐的总时间 public int getDuration(){ return mediaPlayer.getDuration(); } ? //是否循环 public void setLooping(boolean isLooping){ mediaPlayer.setLooping(isLooping); } ? //跳转位置 public void seekTo(int mesc){ mediaPlayer.seekTo(mesc); } ? //播放结束 public void setOnCompletionListener(MediaPlayer.OnCompletionListener listener){ mediaPlayer.setOnCompletionListener(listener); } ? //播放错误 public void setOnErrorListener(MediaPlayer.OnErrorListener listener){ mediaPlayer.setOnErrorListener(listener); } ? //播放进度 public void setOnProgressListener(OnMusicProgressListener listener){ musicProgressListener = listener; } ? public interface OnMusicProgressListener{ void OnProgress(int progress,int pos); } }