屏幕关闭时Android MediaPlayer冻结

时间:2016-03-08 21:29:07

标签: android android-mediaplayer freeze

我编写了一个使用MediaPlayer播放MP3文件的音乐播放器应用程序。它大部分时间都可正常工作,但是当我关闭手机屏幕时,prepare()方法可以冻结,直到我打开屏幕。一旦屏幕打开,它就会消失。

这非常令人沮丧,因为它并不总是发生,但是在屏幕关闭后播放约3首曲子后发生。我没有任何例外。

mMediaPlayer.reset();

LogDebugf(  "MP3_PLAY::mMediaPlayer.setDataSource..\n" );
mMediaPlayer.setDataSource( mMP3Path );

LogDebugf(  "MP3_PLAY::mMediaPlayer.prepare..\n" );
mMediaPlayer.prepare();

// Can freeze for long times or until screen turned on in above call
LogDebugf(  "MP3_PLAY::mMediaPlayer.start..\n" );
mMediaPlayer.start();

我的实际Logcat如下所示:

03-09 08:04:07.333 I/System.out( 8186): MP3_PLAY::mMediaPlayer.prepare..
03-09 08:04:07.333 V/MediaPlayer( 8186): setVideoSurfaceTexture
// Notice the huge delay here until I switch the screen on
03-09 08:04:31.049 V/MediaPlayer( 8186): prepare
03-09 08:04:31.059 V/MediaPlayer( 8186): message received msg=200, ext1=973, ext2=0
03-09 08:04:31.059 W/MediaPlayer( 8186): info/warning (973, 0)
03-09 08:04:31.059 V/MediaPlayer( 8186): callback application
03-09 08:04:31.059 V/MediaPlayer( 8186): back from callback
03-09 08:04:31.059 V/MediaPlayer( 8186): message received msg=5, ext1=0, ext2=0
03-09 08:04:31.059 V/MediaPlayer( 8186): New video size 0 x 0
03-09 08:04:31.059 V/MediaPlayer( 8186): callback application
03-09 08:04:31.059 V/MediaPlayer( 8186): back from callback
03-09 08:04:31.059 V/MediaPlayer( 8186): message received msg=1, ext1=0, ext2=0
03-09 08:04:31.059 V/MediaPlayer( 8186): prepared
03-09 08:04:31.059 V/MediaPlayer( 8186): signal application thread
03-09 08:04:31.059 V/MediaPlayer( 8186): callback application
03-09 08:04:31.059 V/MediaPlayer( 8186): prepare complete - status=0
03-09 08:04:31.059 V/MediaPlayer( 8186): back from callback
03-09 08:04:31.059 I/System.out( 8186): MP3_PLAY::mMediaPlayer.start..

冻结之前出现的最后一行是“setVideoSurfaceTexture”,然后在约30秒后我开启屏幕后才会处理'prepare'。

更新:我甚至尝试过prepareAsync(),它也有同样的问题。这是三星Galaxy S4。如果我不能可靠地工作,我可以试试ExoPlayer。

1 个答案:

答案 0 :(得分:0)

我相信下面缺少的一行解决了我的问题:

mMediaPlayer.setWakeMode( getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK );

但..

更糟糕的是,在重新启动手机后,我无法播放上述任何音乐!

现在我明白了:

03-10 18:29:09.857 V/MediaPlayer( 2119): message received msg=100, ext1=1, ext2=-2147483648
03-10 18:29:09.857 E/MediaPlayer( 2119): error (1, -2147483648)
03-10 18:29:09.857 V/MediaPlayer( 2119): callback application
03-10 18:29:09.857 V/MediaPlayer( 2119): back from callback
03-10 18:29:09.877 I/MediaPlayer( 2119): send context aware event
03-10 18:29:09.877 I/MediaPlayer( 2119): sendBroadcast CONTEXT_AWARE_MUSIC_INFO - type(error) - id (4)
03-10 18:29:09.877 E/MediaPlayer( 2119): Error (1,-2147483648)
03-10 18:29:09.877 I/System.out( 2119): OnErrorListener::MP3 ERROR 1 -2147483648

在MediaPlayer工作之前,我需要等待手机准备就绪。在选择物品直到它完全醒来之前,它甚至不会发出哔哔声。