Android MediaPlayer getCurrentPosition滞后

时间:2015-02-10 17:28:08

标签: java android media-player android-mediaplayer

各位大家好,希望你们能帮我解决这个问题:

我有一个MediaPlayer实例,指向本地存储中的mp3文件和链接到播放的搜索栏。一切都很好,直到我启动更新seekBar的线程(通过Handler.postDelayed或AsynTask)。

每次调用 player.getCurrentPosition(); 时,都会在我的应用程序中听到一个小的延迟,这很尴尬。有没有办法调用此方法而不会产生这种效果?还有其他方法可以跟踪播放吗?

他是启动媒体播放器的代码:

    Uri uri = Uri.fromFile(mp3);
    player = new MediaPlayer();
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {
        player.setDataSource(getApplicationContext(), uri);
        player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                playerSeek.setMax(player.getDuration());
                playerSeek.setProgress(0);

                // 3. Start playing the reel.
                onPlayAction(findViewById(R.id.playButton));
                AsyncTask<Void, Integer, Void> playback = prepareSeekUpdater();

                player.start();
                playback.execute();
            }
        });
        player.prepareAsync();
    } catch (IOException e) {
        Log.e(TAG, String.format("Couldn't load the mp3 %s", mp3.getName()), e);
        return;
    }

这是为搜索栏更新创建AsyncTask的代码:

    private AsyncTask<Void, Integer, Void> prepareSeekUpdater(){
    return new AsyncTask<Void, Integer, Void>() {
        /** {@inheritDoc} */
        @Override
        protected Void doInBackground(Void... params) {
            // 1. if the player has started and while the
            // playback is running, the seek bar will be updated and once the playback
            // is finished or interrupted, the thread will be stopped.
            if (null == player) {
                return null;
            }

            int progress;
            while (player.isPlaying() && !isCancelled()) {
                progress = player.getCurrentPosition();
                publishProgress(progress);
                // Wait a little bit.
                try {
                    Thread.sleep(Constants.SEEKER_DELAY);
                } catch (InterruptedException e) {
                    Log.e(TAG, String.format("Couldn't update seek bar."),e);
                }
            }

            return null;
        }

        /** {@inheritDoc} */
        @Override
        protected void onProgressUpdate(Integer... values) {
            playerSeek.setProgress(values[0]);
        }
    };
}

0 个答案:

没有答案