Android:mediaplayer因未处理的事件而离开

时间:2012-03-07 21:37:58

标签: android media-player

我需要获取需要从应用播放的一系列语音通知的音频文件的持续时间。我已将音频文件添加为资源,它们确实可以正常播放。下面的示例代码实际上完全符合其预期目的:它确实返回音频文件的持续时间。

以下是代码:

float getDurationOfAudioResource(LocationEnum loc, Context context){
    float  duration = 0;
    try {
        MediaPlayer mp; 
        mp = MediaPlayer.create(context, getAudioResource(loc));
        duration = mp.getDuration();
        mp.release();
        mp = null;
    }
    catch (IllegalStateException e) {e.printStackTrace(); logError(25, "TestDescItem:Fault::Could not open mediaplayer object with audio resource.");} 
    return duration;
}

这是奇怪的事情。此代码在Main活动中调用,该活动为给定测试准备一组音频指令。此活动中没有错误。但是一旦调用了第二个活动,我就会在logcat上遇到一长串错误。

03-07 13:23:43.820: I/ActionLogger(21435): GenTest_Info_Test #0 successfully created.
03-07 13:23:43.830: I/ActionLogger(21435): GenTest_Info_Test #1 successfully created.
03-07 13:23:43.840: I/ActionLogger(21435): GenTest_Info_Test #2 successfully created.
03-07 13:23:43.850: I/ActionLogger(21435): GenTest_Info_Test #3 successfully created.
<snip>
03-07 13:23:43.910: I/ActionLogger(21435): GenTest_Info_all tests successfully created.
03-07 13:23:47.260: W/MediaPlayer(21435): mediaplayer went away with unhandled events
03-07 13:23:47.260: W/MediaPlayer(21435): mediaplayer went away with unhandled events
03-07 13:23:47.260: W/MediaPlayer(21435): mediaplayer went away with unhandled events
03-07 13:23:47.260: W/MediaPlayer(21435): mediaplayer went away with unhandled events
03-07 13:23:47.260: W/MediaPlayer(21435): mediaplayer went away with unhandled events
03-07 13:23:47.260: W/MediaPlayer(21435): mediaplayer went away with unhandled events
03-07 13:23:47.260: W/MediaPlayer(21435): mediaplayer went away with unhandled events
03-07 13:23:47.260: W/MediaPlayer(21435): mediaplayer went away with unhandled events
03-07 13:23:47.270: W/MediaPlayer(21435): mediaplayer went away with unhandled events
<snip>

我已经单步升级到主要活动的末尾(没有错误)和第二个活动的第一行。这些活动之间肯定会产生错误 此外,如果我注释掉try块的八行(因此只返回零),则可以避免logcat错误。当我恢复八行时,错误会恢复。 我已经挖掘了文档并搜索了网页,我相信我正在构建,发布和销毁媒体播放器对象,所以我不明白为什么我会收到错误。 那就是说,我一定是做错了。有什么想法吗?

谢谢,

凯文

2 个答案:

答案 0 :(得分:179)

只需将mp.reset();放在mp.release();之前。

答案 1 :(得分:41)

神圣的五个人:

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