Android报告媒体播放器currentposition到progressbar或其他什么

Ahm*_*ck' 2 android runnable android-mediaplayer

在我的情况下,我想流式传输音频并在简单的ProgressBar上显示其进度,我找不到用于播放进度的事件处理程序,我在互联网上发现的是我可以制作一个Runnable并在play()上将其激活为如下

public void fireRunnable()
{
    Runnable runnable = new Runnable()
    {
        @Override
        public void run()
        {
            int duration = mediaPlayer.getDuration();
            while( mediaPlayer.isPlaying() )
            {
                Log.v("", mediaPlayer.getCurrentPosition()+"");
            }
        }
    };
    runnable.run();
}
Run Code Online (Sandbox Code Playgroud)

在onPrepared()中播放后立即调用它

@Override
public void onPrepared(MediaPlayer arg0)
{
    arg0.start();
    fireRunnable();
}
Run Code Online (Sandbox Code Playgroud)

现在这首歌开始没有音频和应用程序崩溃在5秒后,这是一个很好的方法,如果是的话我怎么能让它工作?或者我没有其他选择?
帮助将不胜感激.

Dav*_*ave 5

如果您选择使用Runnable已显示的,则需要在另一个中运行它Thread并使用post(Runnable)在UI线程上进行更改.你提到的崩溃可能是因为你的UI线程上有一个非常活跃的while循环.即使启动一个单独的线程,您也需要Thread.sleep(long)在循环中调用以产生一些处理器时间,因为您的进度条不需要非常准确.

另一种方法是使用postDelayed(Runnable, long)一个Runnable反复重新帖子本身后延迟一段时间(例如,500毫秒).根据具体情况,这种方法可能是首选,因为它避免了额外的线程.

此外,您应该注意,isPlaying()如果MediaPlayer暂停,则为false .最好使用布尔成员作为停止更新进度条的条件.在开始更新进度条之前将其设置为true,并在OnCompletionListener.onCompletion()回调中将其设置为false MediaPlayer.

编辑:

当我提到post(Runnable)UI线程时,我指的是从其他线程更改UI元素是非法的.在这种情况下,您可能没有明确更改UI元素,只有进度条的状态,这应该没问题.

编辑:( postDelayed版本)

在你的Activity:

private boolean mUpdateProgress = false;
private Runnable mUpdateRunnable = new Runnable() {
    @Override
    public void run() {
        // update progress bar using getCurrentPosition()
        if (mUpdateProgress)
            postDelayed(mUpdateRunnable, 500);
    }
}
private MediaPlayer.OnCompletionListener mComplete =
    new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion() {
            mUpdateProgress = false;
        }
    }
Run Code Online (Sandbox Code Playgroud)

无论您在何处创建MediaPlayer,请致电:

mediaPlayer.setOnCompletionListener(mComplete);
Run Code Online (Sandbox Code Playgroud)

无论你在哪里开始MediaPlayer,都要这样做:

// update the duration of the progress bar
mUpdateProgress = true;
post(mUpdateRunnable); // or simply mRunnable.run() if you are on the main thread
mediaPlayer.start();
Run Code Online (Sandbox Code Playgroud)