Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 814
Zahid Habib Avatar asked Apr 15 '12 06:04

Zahid Habib


People also ask

What API used for playback audio and video files?

MediaPlayer. This class is the primary API for playing sound and video.

How Audio files can be play through media player in Android?

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.

What is Media API in Android?

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).

How do I play music in the background on my Android?

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.


2 Answers

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.

like image 180
Zar E Ahmer Avatar answered Oct 15 '22 05:10

Zar E Ahmer


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();
}
like image 42
dakshbhatt21 Avatar answered Oct 15 '22 07:10

dakshbhatt21