我正在尝试收听我创建的媒体播放器的OnInfoListener,以便在缓冲开始和结束时获取.
由于某种原因,事件永远不会发生.
这是我的初始化代码
private void initPlayer(Surface s){ mPlayer = new MediaPlayer(); mPlayer.setSurface(s); mPlayer.setOnCompletionListener(this); mPlayer.setOnErrorListener(this); mPlayer.setOnInfoListener(this); mPlayer.setOnPreparedListener(this); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mPlayer.setDataSource(file_url); mPlayer.prepare(); } catch (IllegalArgumentException e) { OnError(PLAYER_ERRORS.player_not_loaded,e.getMessage() + ""); } catch (SecurityException e) { OnError(PLAYER_ERRORS.player_not_loaded,e.getMessage() + ""); } catch (IllegalStateException e) { OnError(PLAYER_ERRORS.player_not_loaded,e.getMessage() + ""); } catch (IOException e) { OnError(PLAYER_ERRORS.no_connection,e.getMessage() + ""); } }
这是我的倾听者
@Override public boolean onInfo(MediaPlayer mp,int what,int extra) { if(what == MediaPlayer.MEDIA_INFO_BUFFERING_START) { OnEvent(PLAYER_EVENT.buffering_start); } else if(what == MediaPlayer.MEDIA_INFO_BUFFERING_END) { OnEvent(PLAYER_EVENT.buffering_end); OnGotDuration(getDuration()); } return what == MediaPlayer.MEDIA_INFO_BUFFERING_START || what == MediaPlayer.MEDIA_INFO_BUFFERING_END; }
有人可以帮我理解为什么会这样吗?
谢谢
解决方法
显然这是Android中的一个已知错误.
在播放HLS流时,它永远不会调用OnInfoListener或OnBuffering.
在播放HLS流时,它永远不会调用OnInfoListener或OnBuffering.
查看here了解更多详情
我所谓的解决方案是创建一个现在沿着播放器一侧运行的线程,并不时检查其进度以确定播放是否停止 – 假设这意味着播放器正在缓冲.
这是我想要的代码
private class BufferingThread extends Thread{ WeakReference<NewDefaultPlayer> player; long currentPos,lastSecond; boolean isBuffering,alreadyBuffering; private Object locker = new Object(); public BufferingThread(NewDefaultPlayer player) { this.player = new WeakReference<NewDefaultPlayer>(player); } private Runnable BufferStart = new Runnable() { public void run() { player.get().OnEvent(PLAYER_EVENT.buffering_start); } }; private Runnable BufferStop = new Runnable() { public void run() { player.get().OnEvent(PLAYER_EVENT.buffering_end); } }; @Override public void run() { super.run(); while(true) { synchronized (locker) { currentPos = player.get().getCurrentPosition(); isBuffering = currentPos == 0 ? true : currentPos <= lastSecond; lastSecond = (int) currentPos; if(alreadyBuffering){ if(!isBuffering) { if(player.get().getPlayerState().equals(PLAYER_STATES.IS_PLAYING)) { alreadyBuffering = isBuffering; TvinciSDK.getMainHandler().post(BufferStop); } } } else { if(isBuffering){ alreadyBuffering = isBuffering; TvinciSDK.getMainHandler().post(BufferStart); } } try { sleep(1500); } catch (InterruptedException e) { break; } } } } } //Stop the thread if the user has stopped the video private void handleBufferingWorkaround(boolean work){ if(bThread == null) bThread = new BufferingThread(this); if(work){ if(!bThread.isAlive()) bThread.start(); } else if(bThread.isAlive()) { bThread.interrupt(); bThread = null; } }
希望能帮助到你