媒体播放器准备时的进度条



当我的媒体播放器准备流媒体文件时,我正试图弄清楚如何在进度条上显示"正在加载。请稍候…"。现在发生的是,它在歌曲准备好后显示。我该怎么解决这个问题?

        mediaPlayerLoadingBar =ProgressDialog.show(PlaylistActivity.this, "", "Loading. Please wait...", true);         
                    /*dubstep stream*/
                    try {
                        dubstepMediaPlayer.setDataSource(dubstepPlaylistString[0]);
                        dubstepMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        dubstepMediaPlayer.prepare();
                    } catch (IllegalArgumentException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (SecurityException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IllegalStateException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    dubstepMediaPlayer.start();
                    if(dubstepMediaPlayer.isPlaying()){
                        mediaPlayerLoadingBar.dismiss();
                    }`

编辑:这是我现在的代码:

`交换机(pSelection){案例1:

                    new AsyncTask<Void, Void, Void>(){
                    @Override
                    protected void onPreExecute(){
                        mediaPlayerLoadingBar =ProgressDialog.show(PlaylistActivity.this, "", "Loading. Please wait...", true);
                        try {
                            dubstepMediaPlayer.setDataSource(dubstepPlaylistString[0]);
                        } catch (IllegalArgumentException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IllegalStateException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        dubstepMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    }
                    @Override
                    protected Void doInBackground(Void... params) {
                        // TODO Auto-generated method stub
                        //mediaPlayerLoadingBar =ProgressDialog.show(PlaylistActivity.this, "", "Loading. Please wait...", true);
                        return null;
                    }
                    protected void onPostExecute(Void result){
                        //mediaPlayerLoadingBar =ProgressDialog.show(PlaylistActivity.this, "", "Loading. Please wait...", true)
                            dubstepMediaPlayer.prepareAsync();
                        dubstepMediaPlayer.start();
                        mediaPlayerLoadingBar.dismiss();
                }
                }.execute();`

如果有人仍然面临这个问题,这里是下面的代码

      AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
            @Override
            protected void onPreExecute() {
                if(translation.equals("NIV"))
                {
                    if(AudioPlaying==false)
                    {
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setOnPreparedListener(Main.this);
                        mediaController = new MediaController(Main.this);
                    }
                    else
                        mediaController.show();
                }
                else
                    Toast.makeText(getBaseContext(), "عفوا, جاري تحميل ملفات الصوت الخاصة بترجمة الفانديك ", Toast.LENGTH_LONG).show();
                pd = new ProgressDialog(Main.this);
                pd.setTitle("Processing...");
                pd.setMessage("Please wait.");
                pd.setCancelable(false);
                pd.setIndeterminate(true);
                pd.show();
            }
            @Override
            protected Void doInBackground(Void... arg0) {
                try {
                    //Do something...
                    //Thread.sleep(5000);
                    try 
                    {
                        mediaPlayer.setDataSource(AudioUrlPath);
                        mediaPlayer.prepare();
                        mediaPlayer.start();
                        AudioPlaying=true;
                    } 
                    catch (IOException e) {
                        Log.e("AudioFileError", "Could not open file " + AudioUrlPath + " for playback.", e);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void result) {
                if (pd!=null) {
                    pd.dismiss();
                    //b.setEnabled(true);
                }
            }
        };
        task.execute((Void[])null);

问题在于你在这里没有异步地做任何事情,你应该这样做。你应该使用AsyncTask来完成你的工作。

看看"4个步骤",如这里详细介绍的:

4步

当执行异步任务时,该任务将经过4个步骤:

  1. onPreExecute(),在任务执行后立即在UI线程上调用。此步骤通常用于设置任务实例,方法是在用户界面中显示进度条
  2. doInBackground(Params…),在onPreExecute()完成执行后立即在后台线程上调用。使用此步骤以执行可能需要很长时间的背景计算。这个异步任务的参数被传递给这个步骤。这个此步骤必须返回计算结果返回到最后一步。此步骤还可以使用publishProgress(Progress…)以发布一个或多个进度单位。这些值发布在UI线程上,位于onProgressUpdate(进度…)步骤
  3. onProgressUpdate(Progress…),在调用publishProgress(Progress..)后在UI线程上调用。执行的时间为未定义。此方法用于显示用户界面,而后台计算仍在执行。例如,它可以用于为进度条设置动画或在中显示日志文本字段
  4. onPostExecute(Result),在后台计算完成后在UI线程上调用。背景的结果将计算作为参数传递到该步骤

编辑:

你可以创建一个匿名的内部类来进行竞价,这可能与你创建onClick处理程序的方式类似。在你的onClick中做这样的事情:

//pseudo-code...
onClick(View v, ...) {
    new AsyncTask<Generic1, Generic2, Generic3>() {
        protected void onPreExecute() {
            // do pre execute stuff...
        }
        protected Generic3 doInBackground(Generic1... params) {
            // do background stuff...
        }
        protected void onPostExecute(Generic3 result) {
            // do post execute stuff...
        }
    }.execute();
}

别忘了在这里关注你的仿制药!

这是活动类。我只是在给你指路。

package com.android.mediaactivity;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
    public class MediaActivity extends Activity 
    {
        public LinearLayout mainLayout;
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            mainLayout=(LinearLayout)findViewById(R.id.mainlinear);
            MediaPlayer media=new MediaPlayer(this);
            media.startPlayer();
        }
    }

这是mediaplayerclass。

package com.android.mediaactivity;
import java.io.IOException;
import android.media.MediaPlayer.OnPreparedListener;
public class MediaPlayer implements OnPreparedListener {
    MediaActivity mediaActivity;
    android.media.MediaPlayer mediaPlayer;
    public MediaPlayer(MediaActivity mediaActivity) {
        this.mediaActivity = mediaActivity;
    }
    public void startPlayer() {
        mediaPlayer = new android.media.MediaPlayer();
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource("");
            mediaPlayer.prepareAsync();
            toggleProgress(true);
        } catch (IllegalArgumentException e) { // TODO Auto-generated catch block          e.printStackTrace();        } catch (IllegalStateException e) {             // TODO Auto-generated catch block          e.printStackTrace();        } catch (IOException e) {           // TODO Auto-generated catch block          e.printStackTrace();        }   }   public void onPrepared(android.media.MediaPlayer mp)    {       toggleProgress(false);      mediaPlayer.start();    }
            public void toggleProgress(final boolean show) {
                mediaActivity.runOnUiThread(new Runnable() {
                    public void run() {
                        if (show) mediaActivity.mainLayout.setVisibility(mediaActivity.mainLayout.VISIBLE);
                        else mediaActivity.mainLayout.setVisibility(mediaActivity.mainLayout.INVISIBLE);
                    }
                });
            }
        }
    }
}

这是main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:id="@+id/mainlinear"
    android:visibility="invisible">
    <ProgressBar android:id="@+id/ProgressBar01"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></ProgressBar>
</LinearLayout>

当你在底层mediaplayer对象上说prepare时,它在内部确实做了一些准备,比如设置文件的提取器,设置音频解码器来解码编码的音频文件,设置音频接收器来播放解码器解码的原始音频数据。现在这一切都需要时间,而不是瞬间的。

因此,在您的原始代码中,您检查媒体播放器isPlaying,然后将其关闭,但问题是在此时媒体播放器尚未播放音频,因此您的关闭从未被调用,因此始终可见。

您需要做的是实现侦听器MediaPlayer.OnPreparedListener,当在应用程序中调用方法onPrepared时,调用该方法中的解除mediaPlayerLoadingBar.dismiss();

这是我的解决方案:prepareSync函数用于准备音频,它是一个非阻塞操作(它没有阻塞应用程序的主线程)。

然后,当prepareSync返回,音频准备就绪

public void playAudio(String audioFile){

//init the progress dialog
  final ProgressDialog progressDialog = new ProgressDialog(SubjectActivity.this);
    try {
         progressDialog.setCancelable(false);
         progressDialog.setMessage(" Waiting to Prepare ...");
         progressDialog.show();
// pass the url file to the media player
        mediaplayer.setDataSource(audioFile);
        mediaplayer.prepareAsync();

    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
//the callback gets called when prepareAsync audio file become ready, 
    mediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mediaplayer.start();
// cancel the dialog
            progressDialog.cancel();
        }
    });

}

最终发现:伙计们非常Imp点:设置url 后

  try {
            mediaPlayer.setDataSource(url);
        } catch (IOException e) {
            e.printStackTrace();
        }

我添加了prepare_sync()并添加了处理程序,因为它在大文件中崩溃

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        mediaPlayer.prepareAsync();
        ProgressDialog progressDialog = ProgressDialog.show(Player.this,
                "Loading Title", "Loading Message");
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                if (progressDialog != null && progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
            }
        });
        // might take long! (for buffering, etc)
        mediaPlayer.start();
    }
},500);

此代码也将添加进度条。

点数:

  1. 设置url
  2. preparaysnc
  3. OnPreparedlistener进度条

mp.起始-酮

这是我的做法,顺便说一句,我听说有另一种异国玩家,也看看吧!

相关内容

  • 没有找到相关文章

最新更新