Android自带mediaplayer封装,实现播放,暂停,拖动等功能

封装代码工具类: 

public class AudioPlayerUtil {

    private MediaPlayer mPlayer;

    private boolean isInitialized = false;
    private Thread initThread;

    //实现进度条
    private Timer mTimer;
    private Handler mHandler;

    private String url;

    public AudioPlayerUtil(String url) {
        this.url = url;
        mTimer = new Timer();
        mHandler = new Handler();
        initThread = new Thread(() -> init(url));
        initThread.start();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (isPlaying()) {
                    int pos = mPlayer.getCurrentPosition();
                    int duration = mPlayer.getDuration();
                    mHandler.post(() -> {
                        if (mOnSeekListener != null) {
                            mOnSeekListener.OnSeek((int) (pos * 1.f / duration * 100));
                        }
                    });
                }
            }
        }, 0, 1000);


    }

    private void init(String url) {
        mPlayer = new MediaPlayer();
        try {
            mPlayer.setDataSource(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mPlayer.prepareAsync();
        isInitialized = true;

        mPlayer.setOnErrorListener((mp, what, extra) -> {
            //处理错误
            return false;
        });

        //音频播放完成
        mPlayer.setOnCompletionListener(mp -> {
            //start();//播放完成再播放--实现单曲循环
            if (mOnSeekListener != null) {
                mOnSeekListener.onComplete();
            }
            //init(url);
        });

        //音频加载完成可以播放
        mPlayer.setOnPreparedListener(mp -> {
            if (mOnSeekListener != null) {
                mOnSeekListener.loadComplete();
            }
        });

    }

    /**
     * 播放
     */
    public void start() {
        if (mPlayer == null) return;
        if (!isInitialized && mPlayer.isPlaying()) {
            return;
        }
        mPlayer.start();
    }

    /**
     * 是否正在播放
     */
    public boolean isPlaying() {
        if (!isInitialized) {
            return false;
        }
        return mPlayer.isPlaying();
    }

    /**
     * 销毁播放器
     */
    public void onDestroyed() {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.release();//释放资源
            mPlayer = null;
        }
        isInitialized = false;
    }

    /**
     * 停止播放器
     */
    public void stop() {
        if (mPlayer != null && mPlayer.isPlaying()) {
            mPlayer.stop();
        }
    }

    /**
     * 暂停播放器
     */
    public void pause() {
        if (mPlayer != null && mPlayer.isPlaying()) {
            mPlayer.pause();
        }
    }


    /**
     * 跳转到
     *
     * @param pre_100 0~100
     */
    public void seekTo(int pre_100) {
        pause();
        mPlayer.seekTo((int) (pre_100 / 100.f * mPlayer.getDuration()));
        start();
    }


    //------------设置进度监听-----------
    public interface OnSeekListener {
        void OnSeek(int per_100);

        void onComplete();

        void loadComplete();
    }

    private OnSeekListener mOnSeekListener;

    public void setOnSeekListener(OnSeekListener onSeekListener) {
        mOnSeekListener = onSeekListener;
    }

}

使用:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <SeekBar
            android:id="@+id/seek_bar"
            android:layout_width="0dp"
            android:layout_height="5dp"
            android:layout_marginTop="@dimen/dp_10"
            android:layout_marginBottom="@dimen/dp_10"
            android:layout_weight="1" />

        <TextView
            android:id="@+id/tv_index"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0" />

        <TextView
            android:id="@+id/tv_total"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="/100" />

    </LinearLayout>


    <TextView
        android:id="@+id/tv_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/dp_10"
        android:text="start" />

    <TextView
        android:id="@+id/tv_stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/dp_10"
        android:text="stop" />

</LinearLayout>
var url = "xxx.mp3"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_music)

        val musicPlayer = AudioPlayerUtil(url)

        tv_start.setOnClickListener {
            musicPlayer.start()
        }

        tv_stop.setOnClickListener {
            if (musicPlayer.isPlaying) {
                musicPlayer.pause()
            }
        }

        seek_bar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
            }

            override fun onStartTrackingTouch(p0: SeekBar?) {

            }

            override fun onStopTrackingTouch(p0: SeekBar?) {
                p0?.progress?.let { musicPlayer.seekTo(it) }
            }

        })


        musicPlayer.setOnSeekListener(object : AudioPlayerUtil.OnSeekListener {
            override fun OnSeek(per_100: Int) {
                seek_bar.progress = per_100
                tv_index.text = per_100.toString()
            }

            override fun onComplete() {
                seek_bar.progress = 0
                tv_index.text = "0"
            }

            override fun loadComplete() {

            }

        })


    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值