简体   繁体   English

音频缓冲时如何避免单击“播放音频”选项?

[英]How to avoid clicking Play audio option when the audio is buffering?

I am playing an mp3 audio from server using the below code. 我正在使用以下代码从服务器播放mp3音频。 It is working fine, no issues. 它工作正常,没有问题。 But sometimes when clicking on Play button, it is taking few seconds to start the audio, it takes some buffering time, in that gap time if i click Play button again and again, then app crashes. 但是有时,当单击“播放”按钮时,启动音频需要花费几秒钟的时间,这需要一些缓冲时间,如果我一次又一次单击“播放”按钮,则在这段间隔时间内应用程序将崩溃。 How can i have the condition under play button code for checking whether the audio has been buffered and play starting or not? 在播放按钮代码下如何获得条件以检查音频是否已缓冲并开始播放? I can't check here if(mediaPlayer.isPlaying()). 我不能在这里检查(mediaPlayer.isPlaying())。

private void playAudio(String url) throws Exception
{
    if( (mediaPlayer == null || isCompleted) && !isPaused ) {
        isCompleted = false;
        isPaused = false;
        playpauseButton.setBackgroundResource(R.drawable.pauseimage);

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setDataSource(url);
        mediaPlayer.prepare();
        mediaPlayer.start();
    }
    else if ( isPaused ) {
        playpauseButton.setBackgroundResource(R.drawable.pauseimage);
        mediaPlayer.start();
        isPaused = false;
    }
    else {
        playpauseButton.setBackgroundResource(R.drawable.playimage);
        isPaused = true;
        mediaPlayer.pause();
    }

    mediaPlayer.setOnCompletionListener(new OnCompletionListener(){

       @Override
       public void onCompletion(MediaPlayer mp) {
           // TODO Auto-generated method stub
           isCompleted = true;
           isPaused = false;
           playpauseButton.setBackgroundResource(R.drawable.playimage);
       }}
    );
}
public void stopAudio(View view) {
    killMediaPlayer();
}
@Override
protected void onDestroy() {
    super.onDestroy();
    killMediaPlayer();
}
private void killMediaPlayer() {
    isPaused = false;
    isCompleted = true;
    playpauseButton.setBackgroundResource(R.drawable.playimage);

    if(mediaPlayer!=null) {
        try {
            mediaPlayer.release();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}

You can block the user UI with a ProgressDialog or something like that. 您可以使用ProgressDialog或类似的东西来阻止用户界面。

In pseudo-code: 用伪代码:

mediaplayer.setOnPreparedListener(this);
mediaplayer.prepare();
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Preparing the audio");
mProgressDialog.show();

And then when the callback is triggered you can start the mediaplayer: 然后,当回调被触发时,您可以启动mediaplayer:

public void OnPrepared(MediaPlayer mp) {
       mProgressDialog.dismiss();
       mp.start();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM