How to avoid playing 2 music files at a time in android? - android

I am creating an android application where I'm playing a music file from my phone. I am implementing this using services. So there is a problem in my service. When I start the service the music from my app starts playing. When I press Home Key and Went to YouTube application and played any video, The service is still running in the background paying the music file. How can I stop my service from playing the music file, when some other music file is started.
Thanks in advance.

Poll the list of running services on start of a new activity and, if it requires use of the speaker, pause yours and let it finish?

Before starting a new service, stop the running service.
When stopping the running service, make sure you stop the player too.

When the Activity or Service is starting, check whether the music is playing or not. If playing, stop it else return null as below:
I think u have the below lines in your onCreate Method of your Activity:
MediaPlayer mp= MediaPlayer.create(this, R.raw.<Your Music File>);
mp.setLooping(true);
Add the below lines of code in onPause, onStop methods in your Activity:
if(mp.isPlaying())
mp.stop();
else
return;

Create two method like this.
For audio play.
private void playAudioFile()
{
try
{
mp=new MediaPlayer();
mp.reset();
mp.setDataSource(audiofileName));
mp.prepare();
mp.start();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
and this for killMedia player.
private void killMediaPlayer()
{
if(mp != null)
{
try
{
mp.release();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
use this done it's work for me.
and call like this
killMediaPlayer();
playaudio();

Related

How to stop mediaplayer while playing on background?

I am developing a music player on android and the app has two activities (MainActivity and PlayActivity). In the MainActivity I have a listview with a list of songs and in the PlayActivity I have a button to listen and pause the music. The problem is that when go back to MainActivity and I select a new song from the listview, the first one keeps playing on background while the second one also starts playing. How can I stop the first song when I select a new one?
(I don't want to stop mediaplayer onBackPressed, I just want to stop the music when another song it's selected from listview and play a fresh song in PlayActivity)
EDIT: I'm using AsyncTask to start mediaplayer on PlayActivity: mp.prepareAsync();
You could try to stop MediaPlayer when onBackPressed()
MediaPlayer mp ; // mp is your MediaPlayer
#Override
public void onBackPressed() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
super.onBackPressed();
}
private void playMusic() {
if (mp != null) {
if (mp.isPlaying()) {
mp.stop();
mp.release();
MediaPlayer copyMp = new MediaPlayer();
try {
copyMp.setDataSource("/path");
mp = copyMp;
mp.prepare();
mp.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
From here
MediaPlayer is not thread-safe. Creation of and all access to player
instances should be on the same thread.
That means you have to maintain one media player instance throughout your whole application(As per your requirement). I don't know how you implemented the media player(Service/AsyncTask etc.). When you select a new song, you need to access that instance and replace the existing song with the selected one.

using buffering in Android MediaPlayer for playing mp3

I have an url to mp3 file in the internet and want to play it in my app. Now i'm doing it as follows:
private void processPlayRequest(String url) {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.reset();
mPlayer.release();
}
tryToGetAudioFocus();
if (mAudioFocus == AudioFocus.Focused) {
mPlayer = MediaPlayer.create(this, Uri.parse(url));
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mPlayer.setOnPreparedListener(this);
mPlayer.setOnCompletionListener(this);
mPlayer.setOnErrorListener(this);
}
}
It works, but it seems without buffering, i.e. playback begins only after entire mp3 file has been dowloaded. I want to start playback when it becomes possible for faster performance. So i need to use buffering. Is it possible to achieve?
You need to add a MediaPlayer.OnPreparedListener, and call MediaPlayer.prepareAsync(), then call start() from the onPrepared() callback.
You're calling start, reset, release in an incorrect fashion. Why bother starting, if you're going to immediately reset and release?
There's some pretty decent documentation around how to use the class in the developer docs.

Android Mediaplayer should release previous song onCreate activity again

I am in learning process of the Android app development, and trying to create one songs app.
Problem:
I have two activities, A:songslist & B:MediaPlayer
B plays remote song via mp.prepareAsync(); and starts player when its ready.
I want to keep running the song even though I move to other activities or if I open any other app.
But problem comes, when song is running and I go back to select new song, then oncreate activity B it starts streaming and playing new song, since old song is still running.
My Code:
public void Play() {
if(mp.isPlaying())
{
releaseMediaPlayer();
Log.d("MediaPlayer", "Player is already running release it first");
}
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
URL = BASE_URL + album_files[songIndex];
mp.setDataSource(URL);
mp.prepareAsync();
btnPlay.setImageResource(R.drawable.btn_pause);
songTitleLabel.setText("Loading track, please wait....");
}
private void releaseMediaPlayer() {
if (mp != null) {
if(mp.isPlaying()) {
mp.stop();
}
Log.d("MediaPlayer", "Player is released");
mp.release();
mp = null;
}
}
You should have a service for playing music beside playlists and mediaplayer activities. service plays the music even if you exit program and you can have a widget to control playing music.
Try this. Using the answer you can make a background service and also with out background service.
Good luck

How to stop media player properly , android

I have created a list of songs on click on the song i am able to play the song using MedaiPlayer. While one song is playing if the user clicks another song then i am stopping the media player and starting the player again. But I am getting illegalstateexception in reset(). Here is the code where I am getting the exception. How to stop a player properly? also why am i getting this exception. How to avoid it?
public void stopPlayer() {
try {
if (player != null) {
// Log.e("Trying to Stop "," Player ");
player.stop();
player.release();
player.reset();// causes IllegalstateException
player = null;
}
} catch (Exception e) {
player = null;
playerStatus = false;
e.printStackTrace();
}
}
try this :
player.reset();
player.release();
and also have a look at media player state diagram.
If you want to play again ,then use player.reset(),
player.release() means that it releases the player object so you have to re-intialise the player. So first you use reset() and then release(). release() is used when your player object no longer working. When your activity destroys release() method to be used for good practice.
Whenever you want to stop it:
if(player!=null)
{
if(player.isPlaying())
player.stop();
player.reset();//It requires again setDataSource for player object.
}
Whenever your player no longer to be needed:
if(player!=null)
{
if(player.isPlaying())
player.stop();
player.reset();//It requires again setDataSource for player object.
player.release();
player=null; // fixed typo.
}
Though the accepted answer works, This is a better way to achieve the task
private void stopSong() {
if(mediaPlayer!=null) {
if(mediaPlayer.isPlaying()) {
mediaPlayer.reset();// It requires again setDataSource for player object.
mediaPlayer.stop();// Stop it
mediaPlayer.release();// Release it
mediaPlayer = null; // Initialize it to null so it can be used later
}
}
}
Are you planning on reusing the player again, or are you done with the player? If you're done with the player, call release() and not reset(). If you plan on reusing the player, call reset() and not release().
reset() resets the player to its uninitialized state.
release() frees all resources associated with the player.
The Media Player State Diagram shows, and also states:
Calling stop() stops playback and causes a MediaPlayer in the Started, Paused, Prepared or PlaybackCompleted state to enter the Stopped state.
Once in the Stopped state, playback cannot be started until prepare() or prepareAsync() are called to set the MediaPlayer object to the Prepared state again.
That means, that after calling stop(), we should call prepare() on the same audio file if we wish to play it again. Otherwise calling start() again won't do anything.
As prepare() might throw exception, we should wrap it in a try-catch block, like this:
public void stopAudio(View view) {
mplayer.stop();
try {
mplayer.prepare();
} catch (IOException e) {
Log.e("stopAudio", "Unable to prepare() mplayer after stop()", e);
}
}

How do you detect when a sound file has finished?

I am playing a sound file using this code inside a broadcast receiver activity:
notification.sound = Uri.parse("android.resource://emad.app/raw/seven_chimes");
I would like to detect when this file has finished playing.
I tried a loop like this but I think this is only good for the media player because it always = false even though I made sure the sound file was still playing:
/*
* Stay here until the chime sound is finished.
*/
while (manager.isMusicActive()){
}
Can you show me what I should use instead of manager.isMusicActive()?
You can use the MediaPlayer class and add a Completion listener to be activated when the sound finishes playing
MediaPlayer mp = MediaPlayer.create(this,Uri.parse("android.resource://emad.app/raw/seven_chimes"));
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
performOnEnd();
}
});
mp.start();
Not working with broadcast receiver but this is what worked for my current project using Kotlin to track when the audio file has finished playing.
playButton.setOnClickListener {
if (isPlaying) {
pauseSound()
}else {
playSound()
}
mediaPlayer.setOnCompletionListener {
playButton.text = "Play"
isPlaying = false
}
}
isPlaying is boolean, I will explain more if someone is confused. Hope it helps someone else in the future. Happy coding!
try using service to play the music..
after it play once, then stop your service and you can add your program on the onDestroy() service method..
hope it helps :)

Categories

Resources