android 如何知道MediaPlayer中的音轨何时结束?

bvhaajcl  于 2023-03-06  发布在  Android
关注(0)|答案(1)|浏览(169)

我想知道我的音轨何时结束以执行某些操作。
我遇到的问题是,即使设置了mediaPlayer.setLooping(false),OnCompletionListener也不工作
顺便说一句,MediaPlayer正在工作。

mediaPlayer.setOnCompletionListener(mp -> {
                audioIsFinished=true;
                releasePlayer();
                myHolder.play.setImageResource(R.drawable.ic_baseline_play_arrow_24);
                myHolder.divider.setVisibility(View.INVISIBLE);
                myHolder.currentTime.setVisibility(View.INVISIBLE);
                myHolder.seekBar.setVisibility(View.INVISIBLE);
}

holder.play.setOnClickListener(view -> {
            if(holder.getAdapterPosition() == currentPlayingPosition){
                if(mediaPlayer!=null){
                    if(mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                        holder.play.setImageResource(R.drawable.ic_baseline_play_arrow_24);
                    }
                    else {
                        mediaPlayer.start();
                        holder.play.setImageResource(R.drawable.ic_baseline_pause_24);
                    }
                }
            }
            else{
                mediaPlayer = new MediaPlayer();
                fileName = notesList.get(holder.getAdapterPosition()).getPath();
                try {
                    mediaPlayer.setDataSource(fileName);
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                holder.seekBar.setVisibility(View.VISIBLE);
                holder.divider.setVisibility(View.VISIBLE);
                holder.currentTime.setVisibility(View.VISIBLE);
                holder.seekBar.setEnabled(false);
                holder.seekBar.setProgress(0);
   holder.play.setImageResource(R.drawable.ic_baseline_pause_24);
            }
        });
fruv7luv

fruv7luv1#

我用下面的代码解决了这个问题

mediaPlayer.start();
    isMediaPLayerPaused=false;
    new Thread(this::run).start();

    public void run() {
            activity.runOnUiThread(() -> {
                
                    if(!mediaPlayer.isPlaying()&&!isMediaPLayerPaused){
                        //some actions that you want to be done after completion
                    }
                
                new Handler().postDelayed(this::run, 10);
            });
        }

相关问题