Показывать индикатор выполнения при загрузке аудио файла - PullRequest
0 голосов
/ 28 июня 2019

Я довольно новичок в разработке для Android, поэтому я пытаюсь создать приложение, которое может воспроизводить аудио с URL,

Я хочу показать индикатор выполнения во время загрузки аудиофайла из Интернета (некоторые аудиофайлы имеют размер более 15 МБ) Как я могу это сделать?

Вот моя деятельность по воспроизведению аудио

public class AudioPlayerActivity extends AppCompatActivity  {

String Content_id,audio_url;

AudioView audioView;

private ProgressDialog pDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_audio_player);

    audio_url = getIntent().getStringExtra("audio_url");

    // Progress dialog
    pDialog = new ProgressDialog(this);
    pDialog.setCancelable(false);

    audioView=(AudioView)findViewById(R.id.audioview);

    //pDialog.setMessage("Please Wait...");
    //showDialog();

    try {
        audioView.setDataSource(audio_url);
        audioView.start();
    } catch (IOException e) {
        e.printStackTrace();
    }

   //hideDialog();
}


@SuppressLint("MissingSuperCall")
@Override
protected void onStop() {
    super.onPause();
    audioView.pause();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    audioView.pause();
}

private void showDialog() {
    if (!pDialog.isShowing())
        pDialog.show();
}

private void hideDialog() {
    if (pDialog.isShowing())
        pDialog.dismiss();
    }
}

1 Ответ

0 голосов
/ 28 июня 2019

Я делюсь всем кодом для хорошо настроенного MediaPlayer. Просто следуйте и реализуйте это -

public class MusicActivity extends AppCompatActivity implements MediaPlayer.OnCompletionListener, SeekBar.OnSeekBarChangeListener {

    private ImageView cross, settings;
    private TextView titleText;
    private RecyclerView recyclerView;
    private ProgressBar mProgressBar;

    private String id;

    private String title;

    private String audio;

    private String english;
    private String transliteration;
    private String urdu;

    private LinearLayoutManager linearLayoutManager;

    private ProgressDialog progressDialog;

    private float scrollTo;

    private ImageView play_button;

    private View view;
    private TextView audiotitle;
    private LinearLayout hide;
    private ImageView play, rewind, forward;
    private TextView currentTime, endTime;
    private SeekBar seekbar;
    private RelativeLayout progress_layout;
    private LinearLayout offline_layout;
    private ImageView download;
    private ImageView cancel;

    private Dialog mBottomSheetDialog;

    private MediaPlayer mp;
    private Handler mHandler = new Handler();

    private Util util;

    private boolean flag = false;

    private ProgressBar progressBar;

    Boolean isInternetPresent = false;
    ConnectionDetector cd;

    private String open_download_string;

    private ProgressBar mProgress;

    private ArrayList<String> filePath = new ArrayList<String>();

    private int seekForwardTime = 10 * 1000;
    private int seekBackwardTime = 10 * 1000;

    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {
            if (mp != null) {
                long totalDuration = mp.getDuration();
                long currentDuration = mp.getCurrentPosition();

                // Displaying Total Duration time
                endTime.setText(util.milliSecondsToTimer(totalDuration) + " min");
                // Displaying time completed playing
                currentTime.setText(util.milliSecondsToTimer(currentDuration) + " min");

                // Updating progress bar
                int progress = (int) (util.getProgressPercentage(currentDuration, totalDuration));
                seekbar.setProgress(progress);

                mHandler.postDelayed(this, 100);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_player);

        mp = new MediaPlayer();


        cross = (ImageView) findViewById(R.id.cross);
        settings = (ImageView) findViewById(R.id.settings);
        titleText = (TextView) findViewById(R.id.title);
        play_button = (ImageView) findViewById(R.id.play_button);

        setMusicPlayerWidgets();
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {

            title = bundle.getString(Constant.SONG_TITLE);
            audio = bundle.getString(Constant.SONG_AUDIO);


             /*mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){

                    @Override
                    public void onPrepared(MediaPlayer mp) {

                        play_button.setVisibility(View.VISIBLE);

                        if(mp.isPlaying()){
                            if(mp!=null){
                                play_button.setImageResource(R.drawable.pause);
                            }
                        }else{
                            play_button.setImageResource(R.drawable.play);
                        }
                    }
                });*/

              /*  play_button.setVisibility(View.VISIBLE);

                if(mp.isPlaying()){
                    if(mp!=null){
                        play_button.setImageResource(R.drawable.pause);
                    }
                }else{
                    play_button.setImageResource(R.drawable.play);
                }*/

            } else {
                progressBar.setVisibility(View.GONE);
                play_button.setVisibility(View.GONE);
            }

            titleText.setText(title);
        }
    }

    @Override
    public void onResume() {
        super.onResume();


      setUpMusicPlayer();

    }

    /**
     * MUSIC PLAYER IMPLEMENTATION
     **/

    private void setMusicPlayerWidgets() {

        view = getLayoutInflater().inflate(R.layout.media_player_layout, null);
        play = (ImageView) view.findViewById(R.id.play);
        rewind = (ImageView) view.findViewById(R.id.rewind);
        forward = (ImageView) view.findViewById(R.id.forward);
        audiotitle = (TextView) view.findViewById(R.id.title);
        hide = (LinearLayout) view.findViewById(R.id.hide);
        seekbar = (SeekBar) view.findViewById(R.id.seekbar);
        currentTime = (TextView) view.findViewById(R.id.time_current);
        endTime = (TextView) view.findViewById(R.id.time_end);
        progress_layout = (RelativeLayout) view.findViewById(R.id.progress_layout);
        offline_layout = (LinearLayout) view.findViewById(R.id.offline_layout);
        download = (ImageView) view.findViewById(R.id.download);
        cancel = (ImageView) view.findViewById(R.id.cancel);
        mBottomSheetDialog = new Dialog(DuaReadingsActivity.this, R.style.MaterialDialogSheet);
    }

    private void setUpMusicPlayer() {

        audiotitle.setText(title);

        seekbar.setOnSeekBarChangeListener(this);
        mp.setOnCompletionListener(this);

        play_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mp.isPlaying()) {
                    if (mp != null) {
                        play_button.setImageResource(R.drawable.play);
                        play.setImageResource(R.drawable.play_button);
                        mp.pause();
                    }
                } else {
                    play_button.setImageResource(R.drawable.pause);
                    play.setImageResource(R.drawable.pause_button);

                    if (flag == false) {
                        playSong();
                        flag = true;
                    } else {
                        mp.start();
                    }

                    File dirFiles = DuaReadingsActivity.this.getFilesDir();

                    for (String strFile : dirFiles.list()) {
                        filePath.add(strFile);
                    }

                    if (!filePath.contains(open_download_string)) {
                        cd = new ConnectionDetector(DuaReadingsActivity.this);
                        isInternetPresent = cd.isConnectingToInternet();
                        if (isInternetPresent) {

                            new DownloadFileFromURL().execute(audio);

                        } else {
                            cd.noInternetDialog();
                        }
                    }

                    mediaBottomSheet();
                }
            }
        });
    }

    private void mediaBottomSheet() {

        mBottomSheetDialog.setContentView(view);
        mBottomSheetDialog.setCancelable(true);
        mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
        mBottomSheetDialog.show();

        final Handler handler = new Handler();
        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (mBottomSheetDialog.isShowing()) {
                    mBottomSheetDialog.dismiss();
                }
            }
        };

        mBottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
              //  handler.removeCallbacks(runnable);
            }
        });

        handler.postDelayed(runnable, 10000);

        hide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBottomSheetDialog.dismiss();
            }
        });

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mp.isPlaying()) {
                    if (mp != null) {
                        play_button.setImageResource(R.drawable.play);
                        play.setImageResource(R.drawable.play_button);
                        mp.pause();
                    }
                } else {
                    play_button.setImageResource(R.drawable.pause);
                    play.setImageResource(R.drawable.pause_button);

                    if (flag == false) {
                        playSong();
                        flag = true;
                    } else {
                        mp.start();
                    }
                }
            }
        });

        rewind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rewindSong();
            }
        });

        forward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                forwardSong();
            }
        });
    }

    public void rewindSong() {
        if (mp != null) {
            int currentPosition = mp.getCurrentPosition();
            if (currentPosition - seekBackwardTime >= 0) {
                mp.seekTo(currentPosition - seekBackwardTime);
            } else {
                mp.seekTo(0);
            }
        }
    }

    public void forwardSong() {
        if (mp != null) {
            int currentPosition = mp.getCurrentPosition();
            if (currentPosition + seekForwardTime <= mp.getDuration()) {
                mp.seekTo(currentPosition + seekForwardTime);
            } else {
                mp.seekTo(mp.getDuration());
            }
        }
    }

    @Override
    public void onCompletion(MediaPlayer arg0) {

        if (mBottomSheetDialog.isShowing()) {
            mBottomSheetDialog.dismiss();
        }
        play_button.setImageResource(R.drawable.play);
        play.setImageResource(R.drawable.play_button);

        mp.seekTo(0);

        flag = false;

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mp.isPlaying()) {
                    if (mp != null) {
                        play_button.setImageResource(R.drawable.play);
                        play.setImageResource(R.drawable.play_button);
                        mp.pause();
                    }
                } else {
                    play_button.setImageResource(R.drawable.pause);
                    play.setImageResource(R.drawable.pause_button);

                    if (flag == false) {
                        playSong();
                        flag = true;
                    } else {
                        mp.start();
                    }
                }
            }
        });
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        mHandler.removeCallbacks(mUpdateTimeTask);
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mHandler.removeCallbacks(mUpdateTimeTask);
        int totalDuration = mp.getDuration();
        int currentPosition = util.progressToTimer(seekBar.getProgress(), totalDuration);

        // forward or backward to certain seconds
        mp.seekTo(currentPosition);

        // update timer progress again
        updateProgressBar();
    }

    public void playSong() {
        try {
            /*mp.reset();
            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mp.setDataSource(audio);
            mp.prepare();*/
            mp.start();

            play_button.setImageResource(R.drawable.pause);
            play.setImageResource(R.drawable.pause_button);

            seekbar.setProgress(0);
            seekbar.setMax(100);

            updateProgressBar();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } /*catch (IOException e) {
            e.printStackTrace();
        }*/
    }

    public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        try {
            mp.reset();
            mp.prepareAsync();
            mp.stop();
            mp.release();
            mp = null;
        } catch (Exception e) {
            e.printStackTrace();
        }

        final Handler handler = new Handler();
        new Runnable() {
            public void run() {
                finish();
                handler.postDelayed(this, 150);
            }
        };
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        try {
            mp.reset();
            mp.prepareAsync();
            mp.stop();
            mp.release();
            mp = null;
        } catch (Exception e) {
            e.printStackTrace();
        }

        final Handler handler = new Handler();
        new Runnable() {
            public void run() {
                finish();
                handler.postDelayed(this, 150);
            }
        };

        if((mProgress != null) && (mProgress.getProgress() != 0)){
            File file = new File(DuaReadingsActivity.this.getFilesDir() + "/" +open_download_string);
            file.delete();
            if(file.exists()){
                try {
                    file.getCanonicalFile().delete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(file.exists()){
                    getApplicationContext().deleteFile(file.getName());
                }
            }
        }

        // finish();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mp.isPlaying()) {
            mp.pause();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

        if (mp.isPlaying()) {
            mp.pause();
        }
    }

    private class DownloadFileFromURL extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progress_layout.setVisibility(View.VISIBLE);
            download.setVisibility(View.GONE);
            offline_layout.setVisibility(View.GONE);

            mProgress = (ProgressBar) view.findViewById(R.id.circularProgressbar);
            mProgress.setProgress(0);
            mProgress.setSecondaryProgress(100);
            mProgress.setMax(100);
            mProgress.setIndeterminate(false);
            mProgress.setProgressDrawable(getResources().getDrawable(R.drawable.download_progress));
        }

        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();

                int lenghtOfFile = conection.getContentLength();

                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                FileOutputStream outputStream = openFileOutput(audio.substring(audio.lastIndexOf('/') + 1), Context.MODE_PRIVATE);

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;

                    publishProgress((int) ((total * 100) / lenghtOfFile));
                    outputStream.write(data, 0, count);
                }
                outputStream.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(String file_url) {

            getFilesDir().getAbsolutePath();

            progress_layout.setVisibility(View.GONE);
            download.setVisibility(View.GONE);
            offline_layout.setVisibility(View.VISIBLE);

            mProgress.setProgress(0);

        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            mProgress.setProgress(progress[0]);

            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View v) {

                    progress_layout.setVisibility(View.GONE);
                    download.setVisibility(View.VISIBLE);
                    offline_layout.setVisibility(View.GONE);

                    mProgress.setProgress(0);

                    DownloadFileFromURL.this.cancel(true);

                    File file = new File(DuaReadingsActivity.this.getFilesDir() + "/" +open_download_string);
                    file.delete();
                    if(file.exists()){
                        try {
                            file.getCanonicalFile().delete();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if(file.exists()){
                            getApplicationContext().deleteFile(file.getName());
                        }
                    }
                }
            });

            download.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View v) {

                    progress_layout.setVisibility(View.VISIBLE);
                    download.setVisibility(View.GONE);
                    offline_layout.setVisibility(View.GONE);

                    cd = new ConnectionDetector(DuaReadingsActivity.this);
                    isInternetPresent = cd.isConnectingToInternet();
                    if (isInternetPresent) {

                        new DownloadFileFromURL().execute(audio);

                    } else {
                        cd.noInternetDialog();
                    }
                }
            });
        }
    }
}

Это будет отлично работать, если вы будете хорошо следовать. Ура !!

...