在MediaPlayer仍在准备中时停止或释放它 [英] Stop or release MediaPlayer while it is still preparing

查看:214
本文介绍了在MediaPlayer仍在准备中时停止或释放它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个错误还是无法在准备过程中释放,停止或杀死MediaPlayer?

Is it a bug or is it not possible to release, stop or kill MediaPlayer while it's preparing?

我有一个在Service中运行的MediaPlayer实例,如果我停止,释放并将其设置为null,而MediaPlayer处于准备状态,它将停止运行.但是如果我停下来,请放开,如果它处于准备状态,则将其设置为null.

I have an instance of MediaPlayer running in Service, it stops fine if I stop, release, set it to null, while MediaPlayer is in prepared state. But it doesn't if I stop, release, set it to null if it's in preparing state.

onPrepared()调用,并将其设置为null.有一些解决方法吗?

onPrepared() is called after stop, release, setting to null. Some workaround for this?

我认为这是常见的用例,当用户想要在完成准备之前停止MediaPlayer.

I think it's common use case when a user wants to stop MediaPlayer before it has finished preparing.

推荐答案

通过查看

By looking at the MediaPlayer documentation, you're not allowed to call stop() on an uninitialized object; which makes sense because you can't stop what is not running/ready yet.

另一方面,在查看

On the other hand, release() seems to do the trick after looking at the source code of MediaPlayer.

但是添加一个布尔标志来表示不再需要MediaPlayer对象并在调用onPrepared()时使用该标志来释放您的对象并没有什么害处.

But it doesn't harm to add a boolean flag to indicate that there is no need for the MediaPlayer object anymore and use that flag to release your object if onPrepared() gets called.

伪代码如下所示:

public void cancel(){
 mCancel = true;
}

public void onPrepared(MediaPlayer player){
  if(mCancel){
   player.release();
   //nullify your MediaPlayer reference
   mediaPlayer = null
  }
}

这篇关于在MediaPlayer仍在准备中时停止或释放它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆