简体   繁体   English

Media Player创建失败时如何恢复?

[英]Media Player how to recover when create fails?

I have an app that plays randomly every second 1 of 20 different sounds . 我有一个应用程序,它每秒随机播放20种不同声音中的1种。 After almost 1000 successful times the media player create function starts to return always null. 在成功运行近1000次之后,媒体播放器创建函数开始始终返回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. 您的问题是,即使在发布MediaPlayer ,在您再次尝试使用OS时,操作系统可能仍未释放资源,尤其是每秒20次。 I would actually recommend that you look into using a SoundPool instead for something like this. 实际上,我建议您考虑使用SoundPool代替类似的东西。

Regardless, to do this with a MediaPlayer , you should keep only one reference, and reuse that object each time for a different sound. 无论如何,要使用MediaPlayer做到这一点,您应该只保留一个引用,并每次针对不同的声音重用该对象。 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. 我现在播放了10000多个音频,而不再重现错误。

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. 我要感谢kcoppock的帮助,我现在不创建和发布,因为更改数据源要比他解释的要好得多,但这不是主要问题。

The final solution was to convert all the mp3 files into ogg files !!!! 最终解决方案是将所有mp3文件转换为ogg文件!

Media Player has definitely problems with mp3 files. Media Player绝对具有mp3文件问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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