如何正确停止媒体播放器,android
我创建了一个歌曲列表,单击歌曲后我可以使用 MedaiPlayer 播放该歌曲。当一首歌曲正在播放时,如果用户单击另一首歌曲,那么我将停止媒体播放器并再次启动播放器。但我在重置()中遇到非法状态异常。这是我收到异常的代码。如何正确阻止玩家?还有为什么我会得到这个例外。如何避免呢?
public void stopPlayer() {
try {
if (player != null) {
// Log.e("Trying to Stop "," Player ");
player.stop();
player.release();
player.reset();// causes IllegalstateException
player = null;
}
} catch (Exception e) {
player = null;
playerStatus = false;
e.printStackTrace();
}
}
I have created a list of songs on click on the song i am able to play the song using MedaiPlayer. While one song is playing if the user clicks another song then i am stopping the media player and starting the player again. But I am getting illegalstateexception in reset(). Here is the code where I am getting the exception. How to stop a player properly? also why am i getting this exception. How to avoid it?
public void stopPlayer() {
try {
if (player != null) {
// Log.e("Trying to Stop "," Player ");
player.stop();
player.release();
player.reset();// causes IllegalstateException
player = null;
}
} catch (Exception e) {
player = null;
playerStatus = false;
e.printStackTrace();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
试试这个:
并查看媒体播放器状态图。
try this :
and also have a look at media player state diagram.
如果你想再玩一次,那么使用
player.reset()
,player.release()
意味着它释放了播放器对象,因此您必须重新初始化播放器。因此,首先使用reset()
,然后使用release()
。当你的玩家对象不再工作时,使用release()
。当您的活动销毁release()
方法时,可以使用良好的实践。每当你想停止它时:
每当不再需要你的玩家时:
If you want to play again ,then use
player.reset()
,player.release()
means that it releases the player object so you have to re-intialise the player. So first you usereset()
and thenrelease()
.release()
is used when your player object no longer working. When your activity destroysrelease()
method to be used for good practice.Whenever you want to stop it:
Whenever your player no longer to be needed:
虽然接受的答案有效,但这是完成任务的更好方法
Though the accepted answer works, This is a better way to achieve the task
您打算再次使用该播放器,还是已经不再使用该播放器?如果您使用完播放器,请调用release()而不是reset()。如果您打算重用播放器,请调用reset()而不是release()。
reset() 将播放器重置为其未初始化状态。
release() 释放与播放器关联的所有资源。
Are you planning on reusing the player again, or are you done with the player? If you're done with the player, call release() and not reset(). If you plan on reusing the player, call reset() and not release().
reset() resets the player to its uninitialized state.
release() frees all resources associated with the player.
媒体播放器状态图显示并指出:
这意味着,在调用 stop() 后,如果我们想再次播放它,我们应该对同一个音频文件调用prepare()。否则再次调用 start() 将不会执行任何操作。
由于prepare()可能会抛出异常,我们应该将其包装在try-catch块中,如下所示:
The Media Player State Diagram shows, and also states:
That means, that after calling stop(), we should call prepare() on the same audio file if we wish to play it again. Otherwise calling start() again won't do anything.
As prepare() might throw exception, we should wrap it in a try-catch block, like this: