简体   繁体   中英

Media Player how to recover when create fails?

I have an app that plays randomly every second 1 of 20 different sounds . After almost 1000 successful times the media player create function starts to return always null. The problem remains even when I leave the app and I start it again. The only solution is when I install the app again or I switch off and on the device.

Is there any method to recover from this state? If I do release or reset, media player was already null and they produce an exception.

The sequence I do every second is the following:

if (mp != null)
{   
    if (mp.isPlaying()) 
    {
       mp.stop();   
    }   
    if (mp != null) mp.release();   
    if (mp != null) mp = null;  
}   

mp = MediaPlayer.create(this, R.raw.sound);

if (mp !=null)
{
   mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() 
   {           
      public void onPrepared(MediaPlayer mp) 
      {
    if (mp != null) mp.start();
      }
   };
 }
 else
 {
    // error, what should I do here to recover from this situation?
 }

Your problem is that even when you're releasing the MediaPlayer , the OS may not have let go of the resources yet by the time you try to use it again, especially 20 times per second. I would actually recommend that you look into using a SoundPool instead for something like this.

Regardless, to do this with a MediaPlayer , you should keep only one reference, and reuse that object each time for a different sound. Since you're using raw resources for playback, a typically reuse scenario would be something like this:

AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.sound);

//Resets the MediaPlayer state but keeps the resources
mp.reset();

//Sets the data source to the requested sound (R.raw.sound)
mp.setDataSource(afd.getFileDescriptor());

//Prepare the MediaPlayer to play and then start
mp.prepare();
mp.start();

It seems I have found the solution. I have now played more than 10000 audios without reproducing the error anymore.

I want to thank to kcoppock for his help, I do not create and release now because it is much better to change the data source as he explained, but it was not the main problem.

The final solution was to convert all the mp3 files into ogg files !!!!

Media Player has definitely problems with mp3 files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM