Search code examples
androidmedia-player

AndroidStudio MediaPlayer methods pause() and stop() doesnt work correctly


I'm working in a music player that download a File from firebase and init media player with this LOCALFILE. I've trying to STREAM_AUDIO with Media Player, but couldn't make pause() work properly with online streaming. Now, pause/player button only call start() and doesn't pause(); stop() reinit audio immediately. How do I fix that?

Public class PerformanceActivity extends Activity {

    private ImageButton playerPerf, stopPerf;
    protected MediaPlayer mMediaPlayer;
    protected ProgressDialog progressDialog;
    private static String url = "https://firebasestorage.go....";
    private File ARQUIVO_AUDIO;

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

        playerPerf = findViewById(R.id.perfPlayId);
        stopPerf = findViewById(R.id.perfStopId);

        try {
            executarProgressDialog();

            FirebaseStorage storage = FirebaseStorage.getInstance();
            // Create a storage reference from our app
            StorageReference storageRef = storage.getReferenceFromUrl(url);

            final File localFile = File.createTempFile("audios", ".mp3");

            Log.e("MEDIAPLAYER", "localfile criado com sucesso");

            storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {

                    try {

                        mMediaPlayer = new MediaPlayer();
                        mMediaPlayer.setDataSource(localFile.toString());

                        Log.e("MEDIAPLAYER","Media player instanciado");

                        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                            @Override
                            public void onPrepared(MediaPlayer mp) {
                            }
                        });
                        mMediaPlayer.prepareAsync();
                    } catch (IOException e) {
                        Log.e("MEDIAPLAYER",e.toString());
                    }

                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(PerfomanceActivity2.this, "ooops falha no download", Toast.LENGTH_LONG).show();
                    //    progressDialog.dismiss();
                    Log.e("MEDIAPLAYER ERROR", e.toString());
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
        progressDialog.dismiss();

        // Botao play/pause que executa o streaming
        playerPerf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mMediaPlayer!=null) {
                    if (mMediaPlayer.isPlaying()) {
                        mMediaPlayer.pause();
                        Log.e("MEDIAPLAYER", "metodo pause chamado");
                    }
                    if (!mMediaPlayer.isPlaying()) {
                        mMediaPlayer.start();
                        Log.e("MEDIAPLAYER", "start chamado");
                    }
                }
            }
        });
        // Pause o STREAMING e reinicializa o MediaPlayer
        stopPerf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    if (mMediaPlayer != null) {
                        mMediaPlayer.stop();
                        mMediaPlayer.prepare();
                    }
                } catch (Exception e) {
                    Log.e("Audio erro", e.toString());
                }
            }
        });
    }

    //libera espaço da memória quando a Activity é destruida
    @Override
    public void onDestroy() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;

            if (progressDialog != null) {
                progressDialog.cancel();
            }
        }
        super.onDestroy();
    }

    //Metodo que executa um ProgressDialog durante o download do audio
    void executarProgressDialog() {

        try {
            progressDialog = new ProgressDialog(PerfomanceActivity2.this);
            progressDialog.setMessage("Moluscos trabalhando...");
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setTitle("Preparando meditação");
            progressDialog.setCancelable(false);
            progressDialog.show();
        } catch (Exception e) {
            Log.e("ProgressDialog Error", "Erro ao inicializar ProgressDialog");
        }
    }
}

Solution

  • There is an obvious logic problem in playerPerf.OnClickListener.

    if (mMediaPlayer!=null) {
    
        if (mMediaPlayer.isPlaying()) {
    
        mMediaPlayer.pause();
    
        Log.e("MEDIAPLAYER", "metodo pause chamado");
        }
        if (!mMediaPlayer.isPlaying()) { // <= always true because you pause it if not.
    
            mMediaPlayer.start();
    
            Log.e("MEDIAPLAYER", "start chamado");
    
        }
    }
    

    The state mMediaPlayer.isPlaying wasn't separate correctly, which caused => if isPlaying then pauses it, directly considering if !isPlaying is always paused. So it always starts it no matter whether it was playing or not.

    => To solve it:

    Just add a else instead of considering mMediaPlayer.isPlaying() twice.

    if (mMediaPlayer!=null) {
    
        if (mMediaPlayer.isPlaying()) {
    
        mMediaPlayer.pause();
    
        Log.e("MEDIAPLAYER", "metodo pause chamado");
        } else { //<= change it to else
        //if (!mMediaPlayer.isPlaying()) { // <= remove the second if
    
            mMediaPlayer.start();
    
            Log.e("MEDIAPLAYER", "start chamado");
    
        }
    }