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();
}
MediaPlayer. This class is the primary API for playing sound and video.
To play audio or video files in Android, the Android multimedia framework includes the support of MediaPlayer APIs. So, by using MediaPlayer APIs, you can play audio/video files from your Android filesystem or play files from your Application's resource file or even you can stream audio/video files just like Spotify.
The Media APIs are used to play and, in some cases, record media files. This includes audio (e.g., play MP3s or other music files, ringtones, game sound effects, or DTMF tones) and video (e.g., play a video streamed over the web or from local storage).
This example demonstrates how do I play background music in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With