Mediaplayer continues to play - android

I have a media player and everytime that this activity is called if there is a media player playing i want it to stop and the new media player start playing ... This is my audio player method
private void playAudio(String url) throws Exception{
mediaplayer.release();
mediaplayer.setDataSource(url);
mediaplayer.prepare();
mediaplayer.start();
}
I initialize the media player at the beginning of the class
private MediaPlayer mediaplayer = new MediaPlayer();
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.songplaying);
// Getting Our Extras From Intent
Bundle names = getIntent().getExtras();
// Getting Specific Data
path = names.getString("pathkeyword");
//Start Player
try {
playAudio(path);
} catch (Exception e) {
e.printStackTrace();
}
Everytime this is class is created it creates a new media player doesn't stop the other one and just plays both at the same time.

You may wish to look into onPause and kill the media player then. The problem is that there is no reference to the media player once it has been made a 2nd time. As a result, you start up your activity, play the music, but when you exit (e.g. press the HOME button) the media player has not been told to stop (it runs as a separate thread). When you reopen it, it will start a new media player on a new thread, producing two sounds.
To fix this, kill the media player properly when you exit. This will properly kill the media player when you quit the activity:
#Override
protected void onPause(){
super.onPause();
if(mediaplayer.isPlaying()){
try{
mediaplayer.stop();
}
catch(IllegalStateException){
Log.d("mediaplayer","Media player was stopped in an illegal state.");
}
}
}
If you wish to continue the music whilst the activity is not in the foreground, you need to use a Service.

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.

How to release media player while preparing

I am working on music player app where I am doing streaming of music using MediaPlayer. Streaming is working fine but now I want If user press back button of the activity then it should stop preparing & release media player immediately.
Currently when it is preparing and if activity is being destroyed then I am releasing the MediaPlayer like this but when it release it then it hangs the application & show ANR.
#Override
protected void onDestroy() {
super.onDestroy();
if(mediaPlayer!=null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
I am initializing MediaPlayer like below
mediaPlayer = null;
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource("http://www.samisite.com/sound/cropShadesofGrayMonkees.mp3");
Now I want when it start preparing then on back press when I am releasing in onDestory then it should not hang the app & release the media player smoothly.
Please help me what is the best way to do this. Thanks in advance
mediaPlayer.prepareAsync();
Check the answer here. And the MediaPlayer State Diagram from android code.
Edit:
#TGMCians I showed him the provided link, So, if the playback is still not ready or preparing, he can not call stop() until it's called onPrepared. I'm not sure that onPrepared keep called after the app onDestroy called. So, The full snip I think is:
private boolean mPrepared = false;
private boolean mCancel = false;
public void onPrepared(MediaPlayer player){
mPrepared = true;
if(mCancel){
player.release();
mPrepared = false;
mCancel = false;
//nullify your MediaPlayer reference
mediaPlayer = null;
}
}
private void cancelMedia(){
mCancel = true;
}
#Override
protected void onDestroy() {
super.onDestroy();
cancelMedia();
if (mediaPlayer != null && mPrepared) {
mediaPlayer.stop();
mediaPlayer.release();
mPrepared = false;
mediaPlayer = null;
}
}

two media player played at once

i create an app, and in one layout (just call it layout A), i play the media player, then when i went to another layout (just call it Layout B), i want the sound from the Layout A is continue playing in Layout B, and when i went back to the Layout A, i also want the media player is still continuing the music that was played before.
In Layout A, i set this code in onCreate:
player = MediaPlayer.create(this, R.raw.sound);
if(!isMuted())
{
player.setLooping(true);
player.start();
}
...
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
Intent intent = new Intent(A.this, B.class);
stop=1;
startActivity(intent);
}
});
And this code:
#Override
protected void onPause()
{
super.onPause();
if (stop!=1)
{
//stop=1 if i go to another layout, for example when i want to go to Layout B
//if the device is automatically locked, i want the media player is paused and it resumed when i unlock the device, so i use stop!=1 to know whether the sound should be paused or not
player.pause();
length = player.getCurrentPosition();
}
}
#Override
protected void onResume()
{
super.onResume();
if(!isMuted())
{
//isMuted is method to know whether the sound is muted or not, if it isn't muted, then the sound is resumed
player.seekTo(length);
player.setLooping(true);
player.start();
}
}
In layout B, i used this code in onCreate:
player = MediaPlayer.create(this, R.raw.sound);
....
And this code:
protected void onPause()
{
super.onPause();
player.pause();
length = player.getCurrentPosition();
}
#Override
protected void onResume()
{
super.onResume();
if(!isMuted())
{
if(player.isPlaying())
{
}
else
{
player.seekTo(length);
player.setLooping(true);
player.start();
}
}
}
But this is the problem.
When i went to Layout B, the Media Player from Layout A and Media Player from Layout B is played in the same time, so the sound is played simultaneously at one time.
When i went back to the Layout A, the Media Player in Layout B is stopped and the Media Player in Layout A is stopped and played from the beginning again, it didn't continue the Media Player that was played before.
When the device is locked, the media player is still played although i have used the indicator whether is should be paused or not. Any correction to the code?
I would recommend that you use a Service to play and pause/stop your music. It is not recommended to use Activity to handle music that way. You can start a Service and then play music in it. Services run in background and don't get destroyed automatically too often as compared to Activity. Here's a sample app code that does similar to what you need media player sound continue in all activities
In Activity MediaPlayer can play far.
You should use Service to play MediaPlayer and control from anywhere in application.
I used this tutorial.
https://thenewcircle.com/s/post/60/servicesdemo_using_android_service

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

Mediaplayer won't quit

In my onCreate method i check to see whether a media player is playing and if it is a shut it down
if(mediaplayer.isPlaying()==false)
try {
playAudio(path);
} catch (Exception e) {
e.printStackTrace();
}else{
mediaplayer.stop();
mediaplayer.reset();
}
primarySeekBarProgressUpdater();
}
my play audio method is
private void playAudio(String url) throws Exception{
mediaplayer.setDataSource(url);
mediaplayer.prepare();
mediaplayer.start();
}
i also initialize my media player before the onCreate method. The problem is my media player won't shut down instead when a user clicks on a new song in the list view class it creates this class and plays both media players at the same time the old one continues playing.
Ok, so I assume you have a ListActivity with full of songs, and users click to any of those, it will move to a new Activity to play the song, in which the song information is passed through the Intent.
First of all, you need to read and remember Activity Lifecycle: http://developer.android.com/reference/android/app/Activity.html
Secondly, to your problem, according to the lifecycle, everytime users click to a song on the list, then it will create a new Activity to play the song, that means it creates a new MediaPlayer object as well. Hence, you can see many songs playing as much as you select the songs from the list.
What you need to do is to handle the MediaPlayer object when you close the music-playing screen to return to your song list.
MediaPlayer mPlayer = null;;
public void onCreate() {
// init mediaplayer here
mPlayer = ...
}
public void onDestroy() {
// release object
if( mPlayer != null ) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}

Categories

Resources