Jump to content
Fórum Script Brasil
  • 0
Sign in to follow this  
Carlos Rocha

Buffering em MediaPlayer

Question

Tenho um objeto 

 

MediaPlayer mPlayer = new MediaPlayer();

 

Objetivo: Tocar o Streaming de uma Web Rádio e funciona corretamente.

 

Porém, quando clico em Play, leva um tempo até que a Rádio Web comece a tocar.

 

Existe alguma forma de enquanto o streaming estiver carregando, eu pegar o percentual para passar para uma  SeekBar por exemplo?, 

 

Como?

 

Segue o que eu já fiz:

 

package carcleo.com.player;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import java.io.IOException;

public class player extends AppCompatActivity implements OnBufferingUpdateListener{

    private MediaPlayer mPlayer;
    private String URL;
    private Button btnPlayPause;
    private Boolean conexao = false;
    private SeekBar sb;
    private TextView textView;
    private TextView textView2;
    private TextView textView3;
    private NotificationManager mNotificationManager;
    private AudioManager audioManager;
    private ProgressDialog progressDialog;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.player);
        sb = findViewById(R.id.seekBar);

        textView = findViewById(R.id.textView);
        textView2 = findViewById(R.id.textView2);
        textView3 = findViewById(R.id.textView3);

        progressDialog = new ProgressDialog(this);

        btnPlayPause = (Button) findViewById(R.id.btnPlayPause);

        btnPlayPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    tocaPausa();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        configuraAudioManager();
    }

    private void tocaPausa() throws IOException {
        if (conexao == true) {
            if (!mPlayer.isPlaying()) {
                mPlayer.start();
                btnPlayPause.setBackgroundResource(R.drawable.pause);
            } else {
                mPlayer.pause();
                btnPlayPause.setBackgroundResource(R.drawable.play);
            }
        } else {
            String url = "rtsp://cdn-the-2.musicradio.com:80/LiveAudio/Capital"; // your URL here
            new Play().execute(url);
        }
    }


    private void configuraAudioManager() {
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int volume    = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

        sb.setMax(maxVolume);
        sb.setProgress(volume);

        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, AudioManager.FLAG_SHOW_UI);

                Double total = progress * 6.666666666666667;
                String valor =Integer.toString(Integer.valueOf(total.intValue()));
                textView.setText(valor+" %");

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void notificacao (){

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.home)
                        .setContentTitle("Rádio Capital")
                        .setContentText("Agora deu");

        Intent resultIntent = new Intent(this, player.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(player.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.build());

    }

    private void contaBuffer () {

        textView2.setText(Integer.toString(mPlayer.getDuration()));
        mPlayer.setOnBufferingUpdateListener(
                new MediaPlayer.OnBufferingUpdateListener() {
                    public void onBufferingUpdate(MediaPlayer mp, int percent)
                    {
                        double ratio = percent / 100.0;
                        int bufferingLevel = (int)(mp.getDuration() * ratio);

                        sb.setSecondaryProgress(bufferingLevel);
                        textView2.setText(Integer.toString(bufferingLevel));
                    }

                }

        );

    }


    public void mostraBuffer() {

        mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {

                mediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                    @Override
                    public boolean onInfo(MediaPlayer mp, int what, int extra) {
                        if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END){
                            progressDialog.dismiss();
                            return true;
                        } else if(what == MediaPlayer.MEDIA_INFO_BUFFERING_START){
                            progressDialog.show();
                        }
                        return false;
                    }
                });
            }
        });

    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {

        textView3.setText(Integer.toString(percent));

    }

    class Play extends AsyncTask<String, Void ,Boolean > {

        @Override
        protected void onPreExecute() {

            btnPlayPause.setBackgroundResource(R.drawable.carregando);
            btnPlayPause.setEnabled(false);

        }

        @Override
        protected Boolean doInBackground(String... params) {

            try {
                mPlayer = new MediaPlayer();
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mPlayer.setDataSource(params[0]);
                mostraBuffer();
                mPlayer.prepare(); // might take long! (for buffering, etc)
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }

            return false;
        }
        @Override
        protected void onPostExecute(Boolean result) {

            if (result == true){
                btnPlayPause.setEnabled(true);
                mPlayer.start();
                conexao = true;
                btnPlayPause.setBackgroundResource(R.drawable.pause);
                contaBuffer();
            } else {
                conexao = false;
            }


        }

    }

}
Edited by Carlos Rocha

Share this post


Link to post
Share on other sites

0 answers to this question

Recommended Posts

There have been no answers to this question yet

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  



  • Forum Statistics

    • Total Topics
      148409
    • Total Posts
      643823
×
×
  • Create New...