如何让Android MediaPlayer更快?

时间:2014-01-16 12:51:49

标签: android android-mediaplayer

我有这段代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btSobre = (Button)findViewById(R.id.btInfo);     
    btPlay = (Button)findViewById(R.id.btPlay);

    playTask = new PlayAsyncTask();
    mediaPlayer = new MediaPlayer();

    btPlay.setOnClickListener(new OnClickListener() {           
        @Override
        public void onClick(View v) {
        //playTask.execute();       
            try {
                mediaPlayer.setDataSource("http://************");
            } catch (Exception e) {                 
                e.printStackTrace();
            } 
            try {
                mediaPlayer.prepare();
            } catch (Exception e) {                 
                e.printStackTrace();
            } 

            if(mediaPlayer.isPlaying()){
                mediaPlayer.stop();
                imagemPlay();
            } else {
                mediaPlayer.start();
                imagemPlay();
            }               
        }
    });     

}

//Troca a imagem do botão play. 
private void imagemPlay() {
    if(mediaPlayer.isPlaying()){
        btPlay.setBackgroundResource(android.R.drawable.ic_media_pause);
    } else {
        btPlay.setBackgroundResource(android.R.drawable.ic_media_play);
    }

}

当我按下按钮播放时,播放音乐需要一些时间。我怎样才能更快地获得它或向用户提供一些反馈? 像装载机或其他东西。

1 个答案:

答案 0 :(得分:1)

每次点击播放时都准备好。尝试检查它是否先播放然后停止播放。如果不玩,请完成其余的工作。尝试这个重构的代码,看看它是否有点快:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btSobre = (Button)findViewById(R.id.btInfo);     
    btPlay = (Button)findViewById(R.id.btPlay);

    playTask = new PlayAsyncTask();
    mediaPlayer = new MediaPlayer();

    btPlay.setOnClickListener(new OnClickListener() {           
        @Override
        public void onClick(View v) 
        {

            try 
            {
                imagemPlay();

                if(mediaPlayer.isPlaying())
                {
                    mediaPlayer.stop();
                    return;
                } 

                mediaPlayer.setDataSource("http://************");
                mediaPlayer.prepare();
                mediaPlayer.start();
            } 
            catch (Exception e) 
            {                 
                e.printStackTrace();  
            }
    });     

}

//Troca a imagem do botão play. 
private void imagemPlay() {
    if(mediaPlayer.isPlaying()){
        btPlay.setBackgroundResource(android.R.drawable.ic_media_pause);
    } else {
        btPlay.setBackgroundResource(android.R.drawable.ic_media_play);
    }

}