AndroidStudio MediaPlayer方法pause()和stop()无法正常工作

时间:2018-02-13 01:09:01

标签: android media-player

我正在使用音乐播放器工作,该播放器使用此LOCALFILE从firebase和init媒体播放器下载文件。我已尝试使用Media Player进行STREAM_AUDIO,但无法通过在线流式传输使pause()正常工作。现在, 暂停/播放器按钮只调用start()而不是暂停(); stop()立即重新启动音频。我该如何解决这个问题?

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

1 个答案:

答案 0 :(得分:0)

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

    }
}

状态mMediaPlayer.isPlaying未正确分开,导致=&gt;如果isPlaying然后暂停,直接,考虑!isPlaying是否始终暂停。无论是否正在播放,它总是会启动它。

=&GT;要解决它:

只需添加其他内容,而不是两次考虑mMediaPlayer.isPlaying()

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

    }
}