如果Y已经在播放,如何定义播放Z的按钮?

时间:2014-10-25 08:28:52

标签: android audio media-player android-mediaplayer

我的想法是我有1个按钮和2个状态。 1.按下播放声音Z(来自随机声音列表) 2.第二次按下:如果Z.isPlaying播放Y. 一切似乎都很好,直到我连续按3次,然后得到 nullpointerexception

这是onClick代码:

@Override
    public void onClick(View view) {
        if (view.getId() == R.id.goat) {
            if(Piciu != null) {
                if(mp2.isPlaying()){mp2.stop();mp2.reset();mp2.release();mp2 = null;}
           butGoat.setBackgroundResource(R.drawable.goat96);
            mp3 = MediaPlayer.create(this, R.raw.cow);
            mp3.start();
            butGoat.setBackgroundResource(R.drawable.goat96);
            mp3.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
              public void onCompletion(MediaPlayer mp3) {
                butGoat.destroyDrawingCache();
                butGoat.setBackgroundResource(R.anim.clipeala);
                yourAnimation = (AnimationDrawable) butGoat.getBackground();
                yourAnimation.start();  
                 Piciu = null;
              }
              });
              toast.setText("I can`t yell so Fast!");
              toast.setGravity(Gravity.BOTTOM, 0, 0);
              toast.show();
            } else {
                Piciu = mp2;
        butGoat.destroyDrawingCache();
        butGoat.setBackgroundResource(R.drawable.goat96);
        Random r = new Random();
         int Low = 0;
         int High = 16;
         int rndm = r.nextInt(High-Low) + Low; 
         mp2 = MediaPlayer.create(getApplicationContext(),sounds[rndm]);
                mp2.start();
                mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer mp2) {
                    butGoat.setBackgroundResource(R.anim.clipeala);
                    yourAnimation = (AnimationDrawable) butGoat.getBackground();
                    yourAnimation.start(); 
                     mp2.reset();
                     mp2.release();
                     mp2 = null;
                     Piciu = null;
                }
            }); 
              } 
           }
        }

我无法理解如果Sound Z没有播放,为什么我会得到nullpointerexception。

1 个答案:

答案 0 :(得分:0)

在调用mp2.isPlaying()之前,我发现你没有检查mp2!= null:

    if (view.getId() == R.id.goat) {
        if(Piciu != null) {
            if(mp2.isPlaying()){mp2.stop();mp2.reset();mp2.release();mp2 = null;}

将其更改为if(Piciu!= null&& mp2!= null)也不确定为什么需要Piciu变量。我先清理逻辑,然后清理代码,如果代码仍在崩溃。