0

我有一个应用程序,每秒随机播放 20 种不同声音中的 1 种。近 1000 次成功后,媒体播放器创建函数开始始终返回 null。即使我离开应用程序并重新启动它,问题仍然存在。唯一的解决方案是当我再次安装应用程序或关闭并打开设备时。

有什么方法可以从这种状态中恢复吗?如果我确实释放或重置,媒体播放器已经为空,它们会产生异常。

我每秒执行的顺序如下:

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?
 }
4

2 回答 2

0

看来我找到了解决方案。我现在已经播放了超过 10000 个音频而不再重现错误。

我要感谢 kcoppock 的帮助,我现在不创建和发布,因为按照他的解释更改数据源要好得多,但这不是主要问题。

最终的解决方案是将所有的mp3文件转换成ogg文件!!!!

媒体播放器肯定有 mp3 文件的问题。

于 2012-10-04T20:05:22.157 回答
0

您的问题是,即使您正在释放MediaPlayer,当您再次尝试使用它时,操作系统可能还没有释放资源,尤其是每秒 20 次。我实际上建议您考虑使用 aSoundPool而不是这样的东西。

无论如何,要使用 a 执行此操作MediaPlayer,您应该只保留一个引用,并且每次都重用该对象以获得不同的声音。由于您使用原始资源进行播放,因此典型的重用场景将是这样的:

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();
于 2012-10-02T21:07:45.400 回答