简体   繁体   中英

Android media player is not playing again after stop

I am trying to add media payer in my app. I have two floating action buttons, play and pause. On play, music starts playing, and start fab hides, and pause fab shows. On pressing pause fab, pause fab hides and play fab shows. When I am paying it first time music is playing and stopping but when I am trying to play second time after stopping it music is not playing.

Below is my code:

public class VideoDetail extends AppCompatActivity {

ActivityVideoDetailBinding activityVideoDetailBinding;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    activityVideoDetailBinding = ActivityVideoDetailBinding.inflate(getLayoutInflater());
    setContentView(activityVideoDetailBinding.getRoot());

    ActionBar ab = getSupportActionBar();
    assert ab != null;
    ab.setTitle("Music");
    ab.setDisplayHomeAsUpEnabled(true);

    Intent intent = getIntent();
    String preview = intent.getStringExtra("preview");

    MediaPlayer player = new MediaPlayer();
    Uri uri = Uri.parse(preview);
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {
        player.setDataSource(VideoDetail.this, uri);
        player.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

    activityVideoDetailBinding.fabPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            try {
                activityVideoDetailBinding.fabPlay.hide();
                activityVideoDetailBinding.fabPause.show();
                player.start();

            } catch(Exception e) {
                System.out.println(e.toString());
            }
        }
    });

    activityVideoDetailBinding.fabPause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            activityVideoDetailBinding.fabPause.hide();
            activityVideoDetailBinding.fabPlay.show();
            if(player.isPlaying()){
                player.stop();
            }
        }
    });
  }
}

What am I doing wrong?

Maybe this will help you:

Android Media Player Restart Audio After Calling Stop

Based on this graph:

https://developer.android.com/reference/android/media/MediaPlayer

it all comes down to the fact that you are calling stop() and after that you have to prepare the Mediaplayer again.

You probably mean to call MediaPlayer.pause() instead of stop() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM