Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Carcleo

Buffering em MediaPlayer

Recommended Posts

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


        }

    }

}

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por violin101
      Caros amigos, saudações.
       
      Estou escrevendo um Sistema Java Web e quando clico no Botão Salvar, o Java acusa esse erro:

      ERROR: Cannot invoke "Object.toString()" because the return value of "java.util.Map.get(Object)" is null
       
      Já tentei de várias formas resolver esse problema, mas não estou conseguindo.

      Por favor, alguém pode me ajudar identificar a origem e resolver o problema acima ?

      Grato,
       
      Cesar
    • Por violin101
      Caros amigos, saudações.

      Estou enfrentando um problema que não consigo entender.

      Após Instalar o MySql versão 8.0.36, funciona corretamente realizando as conexões.

      O problema é:
      ---[ após reiniciar o micro, o MySql não faz as conexões.
      --[ tenta localizar este arquivo, mas não acha: my.ini
       
      Onde localizo ou configuro este arquivo na Pasta MySql ?

      Grato,
       
      Cesar
    • Por violin101
      Caros amigos, saudações.
       
      Por favor, preciso de ajuda em Relação a Instalar o Jasper Reports no Eclipse, pois a opção de Eclipse Marketplace, não encontra para instalar.
       
      Já tentei de todas as formas mas não consegui, alguém conhece alguma rotina explicando este procedimento ?
       
      Grato,
       
      Cesar
    • Por violin101
      Caros amantes da informática.
       
      Saudações.
       
      Estou usando o Eclipse Mars versão 4.5.0  e o 4.5.2, acredito que deva ter versões mais novas. 
      Sou novato em JAVA e estou encontrando alguns problema em Instalação de alguns plugins, como por exemplo:
       
      1) quando tento instalar o JBoss Tools através do Eclipse Marteplace, o Eclipse não o encontra na lista de plugins.
      2) se tento instalar através do Install New Software, abaixa alguns arquivos, mas também não instala o JBoss.
      3) se abro o site e arrasto o download para a área de trabalho do Eclipse, também não instala o JBoss.
       
      Caros amigos, existe outra alguma forma de instalar o JBoss Tools no Eclipse e como seria ?
       
      Grato,
       
      Cesar
       
       
    • Por ILR master
      Pessoal, pergunta bem simples. Abaixo tenho o seguinte código:
       
      <script>
      function alerta()
      {
        if (window.confirm("Você realmente quer sair?")) {
          window.open("sair.html");
      }
      }
      </script>
       
      Funciona perfeitamente, só que está abrindo em outra janela e quero que abra na mesma janela.
       
      Alguém pode me ajudar?
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.