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

发布于 2024-11-17 14:18:27 字数 3257 浏览 3 评论 0原文

我试图弄清楚如何在我的媒体播放器准备流文件时显示“正在加载。请稍候...”的进度条。现在发生的事情是在歌曲准备好后显示。我该如何解决这个问题?

        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();
                    }`

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

`switch(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();`

I am trying to figure out how to have a progress bar that says "Loading. Please Wait..." while my media player prepares a streaming file. What occurs now is that it displays after the song is prepared. how can i fix this?

        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();
                    }`

EDIT:
This is the code I have now:

`switch(pSelection){
case 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();`

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

小嗷兮 2024-11-24 14:18:27

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

      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);

If someone Still facing this problem here is the code below

      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);
伤感在游骋 2024-11-24 14:18:27

问题在于您没有在这里异步执行任何操作,而您应该这样做。您应该使用 AsyncTask 来完成您的工作。

看一下“4 个步骤”,详细信息如下:

4个步骤

异步任务执行时,任务会经历4个步骤:

  1. onPreExecute(),在任务执行后立即在 UI 线程上调用。此步骤通常用于设置任务,例如
    例如,在用户界面中显示进度条。
  2. doInBackground(Params...),在 onPreExecute() 执行完成后立即在后台线程上调用。这一步用到了
    执行可能需要很长时间的后台计算。这
    异步任务的参数将传递到此步骤。这
    该步骤必须返回计算结果,并将
    回到最后一步。这一步也可以用
    publishProgress(Progress...) 发布一个或多个单位的进度。
    这些值发布在 UI 线程上,在
    onProgressUpdate(Progress...) 步骤。
  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();
}

不要忘记在这里关注你的泛型!

The issue lies in that you are not doing anything asynchronously here, and you should be. You should use an AsyncTask to do your work.

Take a look at 'the 4 steps', as detailed here:

The 4 steps

When an asynchronous task is executed, the task goes through 4 steps:

  1. onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for
    instance by showing a progress bar in the user interface.
  2. doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used
    to perform background computation that can take a long time. The
    parameters of the asynchronous task are passed to this step. The
    result of the computation must be returned by this step and will be
    passed back to the last step. This step can also use
    publishProgress(Progress...) to publish one or more units of progress.
    These values are published on the UI thread, in the
    onProgressUpdate(Progress...) step.
  3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is
    undefined. This method is used to display any form of progress in the
    user interface while the background computation is still executing.
    For instance, it can be used to animate a progress bar or show logs in
    a text field.
  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background
    computation is passed to this step as a parameter.

EDIT:

You can create an anonymous inner class to do your bidding, which may be similar to how you are creating your onClick handler. In your onClick do something like this:

//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();
}

Don't forget to keep an eye on your generics here!

梦中楼上月下 2024-11-24 14:18:27

这是活动课。这里我只是指路。

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();
        }
    }

这是媒体播放器类。

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>

Here is the activity class.Here i am showing the way only.

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();
        }
    }

Here is 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);
                    }
                });
            }

        }
    }
}

And here is the 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>
柳若烟 2024-11-24 14:18:27

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

因此,在您的原始代码中,您检查媒体播放器是否正在播放,然后将其关闭,但问题是此时媒体播放器尚未播放音频,因此您的关闭永远不会被调用,因此它总是可见的。

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

When you say prepare on the underlying mediaplayer object, internally it really does some preparation like - setting up the extractor for the file, setting up the audio decoder to decode the encoded audio file and setting up the audio sink to play the raw audio data that was decoded from the decoder. Now all this will take time, it is not instantaneous.

So in your original code, you check if the mediaplayer isPlaying and then dismiss it but the problem is at that point of time the mediaplayer is not playing the audio yet and thus your dismiss is never called so it always visible.

What you need to do is implement the listener MediaPlayer.OnPreparedListener and when the method onPrepared is called in your application call the dismiss mediaPlayerLoadingBar.dismiss(); in that method.

装迷糊 2024-11-24 14:18:27

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

然后我使用回调 setOnPreparedListener 在
prepareAsync返回,音频准备好

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();
        }
    });


}

Here is my solution :
The prepareAsync function used to prepare the audio and it is a non blocking operation (it is not blocking the main thread of the app).

Then I used the callback setOnPreparedListener to get notified when the
prepareAsync return, and the audio is ready

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();
        }
    });


}
扮仙女 2024-11-24 14:18:27

终于发现:
伙计们非常小鬼点:
设置 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. 设置
  2. urlprepareasyncOnPreparedlistener

  3. Progressbar

mp.start-done

这是我的做法,顺便说一句,我听说还有替代的 Exoplayer 也可以看看!

Finally found out:
Guys very Imp point:
After setting url

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

I have added prepare_sync() and added handler cause it was crashing for big files

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);

This code will add progressbar too.

Points:

  1. set url
  2. prepareasync
  3. OnPreparedlistener
    Progressbar

mp.start-done

This is my way of doing btw I have heard there is alternative Exoplayer have a look at that too !

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文