简体   繁体   中英

Check if music playing in android media player API

I'm using this code below to play an audio file in android

MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource("fileSourceHere");
mediaPlayer.prepare();
mediaPlayer.start();

I have a button on that program. When click on that button, it'll check if music playing. If music playing, it'll stop that. How can I check if music playing? I tried the code below but it didn't work

if(mediaPlayer.isPlaying() == true){
 mediaPlayer.pause();
}else{
 mediaPlayer.start();
}

To check if Music playing by any other app. Use

AudioManager.isMusicActive();

And if you want to know about your app music.

Add Listener to listen

mediaPlayer.setOnPreparedListener(this);

mediaPlayer.setOnCompletionListener(this);

mediaPlayer.setOnErrorListener(this);

you can add a boolean variable to check isPlaying;

boolean isPlaying= false; //false by default

and when you start mediaPlayer at the very moment set isPlaying=true and you are good to go.

Try this:

MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource("fileSourceHere");
mediaPlayer.prepare();
mediaPlayer.start();

if(mediaPlayer.isPlaying())
{
    //stop or pause your media player mediaPlayer.stop(); or mediaPlayer.pause();
    mediaPlayer.pause();
}
else
{
    mediaPlayer.start();
}
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource("fileSourceHere");

If(mediaPlayer != Null){
if(mediaPlayer.isPlaying() == true)
{ 
mediaPlayer.pause();
}
else
{
 mediaPlayer.start();
}
}
else
{
//mediaPlayer is null
mediaPlayer.start();
}   

I had almost the same problem. Android studio generates an error when you try for the first time because there is no music as datasource. ;)

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