Android中MediaPlayer实现按次数呼叫响铃功能(播放assets下文件)

阿木木 阿木木 | 142 | 2023-01-06

话不多说直接上代码

public class CallMediaPlayer {

    private  MediaPlayer mediaPlayer;
    private  int playbackNum = 7;//播放次数(按14秒算)
    private PlayResultCallBack playResultCallBack;

    //播放回调
    public interface PlayResultCallBack {
        //开始播放
        void onStatrPlay();
        //结束播放
        void onStopPlay();
    }

    /**
     * 开始播放和停止播放的监听设置
     * @param playResultCallBack
     */
    public void setPlayResultCallBack(PlayResultCallBack playResultCallBack ){
        this.playResultCallBack=playResultCallBack;
    }


    /**
     * 开始呼叫响铃
     */
    public  void startCallRinging(Activity activity)  {
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }

        if (mediaPlayer.isPlaying()) {
            return;
        }

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {

                if (playbackNum - 1 != 0) {
                    if (playbackNum != 0) {
                        mediaPlayer.start();
                        playbackNum--;
                    }
                } else {
                    if(playResultCallBack!=null){
                        playResultCallBack.onStopPlay();
                    }
                }
            }
        });

        AssetFileDescriptor afd = null;
        try {
            afd = activity.getResources().getAssets().openFd("hujiao.mp3");
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            mediaPlayer.prepare(); // 准备.

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mediaPlayer.start();//开始
        if(playResultCallBack!=null){
            playResultCallBack.onStatrPlay();
        }

    }



    /**
     * 停止呼叫响铃
     */
    public  void stopCallRinging() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer=null;
        }
    }

}

文章标签: 安卓优化Android
推荐指数:

真诚点赞 诚不我欺~

Android中MediaPlayer实现按次数呼叫响铃功能(播放assets下文件)

点赞 收藏 评论