media player play pause in android

后端 未结 2 1761
暖寄归人
暖寄归人 2021-01-20 15:46

How can I make the Play and Pause image buttons look as a single image button. I am hereby attaching my code below. These are the images used. i Renamed play as start.

相关标签:
2条回答
  • 2021-01-20 16:08

    Change your button to say Play at first. Combine play and pause code into one. Set and check a flag to see if play or pause is pressed and change text accordingly.

    So you'll only have one button and two boolean fields:

     boolean play=true, pause=false;
    
        final Button playPause = (Button) findViewById(R.id.play);
                playPause.setBackgroundResource(R.drawable.start);
    
        playPause.setOnClickListener(mListener);
    

    Now, in your listener code, do this:

    case R.id.play:
    
                if(play)
                {
                    play=false;
                    pause=true;
    
                    //change image for button
                    playPause.setBackgroundResource(R.drawable.start);
    
                    try {
                        mp.prepare();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
    
    
                    mp.start();
                    p.setVisibility(View.INVISIBLE);
                    pu.setVisibility(View.VISIBLE);
                    pu.setClickable(true);
                    p.setClickable(false);
                       //seekBar.setProgress(mp.getCurrentPosition());
                       new Thread(myThread).start();
    
                    }
                if(pause)
                {
                    play=true;
                    pause=false;
    
                     //change image for button
                    playPause.setBackgroundResource(R.drawable.pause);
    
                    mp.pause();
                    pu.setClickable(false);
                    p.setVisibility(View.VISIBLE);
                    pu.setVisibility(View.INVISIBLE);
                    p.setClickable(true);
                }
                break;
    

    Change the text on your button accordingly.

    0 讨论(0)
  • 2021-01-20 16:21

    You can use the following code:

    if(!mp.isPlaying() || isCompleted) {
      isCompleted = false;
      mp.start();
    } else {
      mp.pause();
    }
    

    add a variant:

    private boolean isCompleted = true;
    

    add listener:

    mp.setOnCompletionListener(new OnCompletionListener(){
    
            @Override
            public void onCompletion(MediaPlayer mp) {
                // TODO Auto-generated method stub
                isCompleted = true;
            }}
        );
    
    0 讨论(0)
提交回复
热议问题