MediaPlayer isPlaying() always returning false

2019-02-18 20:20发布

问题:

I am testing on 2 phones. In one device isPlaying() of mediaplayer always return false even when it is playing. but in other device (lg optimus gingerbread) isPlaying() returns true is it is playing else returns false.

Can anyone tell me why this is happening ? My some code depends on this isPlaying() part and i want to make it work on all devices.

public void addSoundMedia(Context context, int resId){
    MediaPlayer mp = MediaPlayer.create(context, resId);
    mp.setVolume(1.0f, 1.0f);
    try{
    mPlayerList.add(mp);
    }
    catch(Exception e){}
}

public void playSoundMedia(int index){
    try{        
    mPlayerList.get(index).start();         
    }
        catch(Exception e){}
}


public MediaPlayer getPlayer(int index){
    return mPlayerList.get(index);
}

Now i am calling

mPlayer.getPlayer(currentPlayingPhraseIndex).isPlaying(); 
//which is now returning false. Previously i was returning true but now it always return false

And i also matched the object, this is the code scenario now:

int phraseIndexToBePlayed = getRandomInteger(0, numberOfPhrasesSelected-1, randomPhraseGen); //get random index from 0 to (size of arraylist where i added my media) -1
currentPlayingPhraseIndex = phraseIndexToBePlayed; //for later use in another function scope

mPlayer.playSoundMedia(phraseIndexToBePlayed);

i also verified if both are same media

mPlayer.getPlayer(currentPlayingPhraseIndex).equals(mPlayer.getPlayer(phraseIndexToBePlayed)); //it returns true so they are both same media

Thanks.

回答1:

MediaPlayer is very odd and very fragile. You have very little you can do to tell what state it is in--and anything you do know could end up wrong.

As a side note, I have discovered that sometimes Eclipse can make apps do VERY strange, inexplicable things. Cleaning the project and restarting Eclipse and uninstalling and reinstalling the app usually takes care of those really wonky things, so always try that when you find an error that seems impossible.

When working with MediaPlayer, track for yourself what it should be doing, and then never, ever trust that MediaPlayer will be in the same state where you left it. Anytime you do anything with the MediaPlayer, be prepared for that lovely IllegalStateException--maybe it was playing, maybe it was prepared, maybe it was paused, but you should be prepared that, at any point, it may be in the wrong state. When you write your code this way, you are less reliant on isPlaying() being accurate.

Not helpful I know, but unfortunately we don't have much in the way of alternatives to MediaPlayer.



回答2:

Also, while we're on the general MediaPlayer subject, note that isPlaying() can cause an ANR when called on the UI thread. In fact, Google recommends executing all MediaPlayer calls from a background handler thread. Which will also serialize execution of MediaPlayer calls.