为什么按钮点击方法播放声音不起作用

时间:2015-10-29 00:01:01

标签: java android audio

我要做的是点击此按钮上的三个声音之一。声音位于首选屏幕中。在按钮上单击它也应该显示动画。目前正在发生的是我将点击按钮,一切都将完美,但随后我停止动画,第二次点击按钮发出声音。当我再次单击该按钮以开始备份动画和声音时我听不到声音,但动画仍然有效。老实说,我不知道什么是错的。这是我的代码......

public void buttonClick() {
    imgView = (ImageView) findViewById(R.id.imageView);
    button = (Button) findViewById(R.id.button);
    blade = (ImageView)findViewById(R.id.imageView4);
    final Animation animRotate = AnimationUtils.loadAnimation(this, R.anim.rotate);
    1stSound = MediaPlayer.create(this, R.raw.file.mp3);
    2ndSound = MediaPlayer.create(this, R.raw.file.mp3);
    3rdSOund = MediaPlayer.create(this, R.raw.file.mp3);

    button.setOnClickListener(

            new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
                    boolean option1 = getPrefs.getBoolean("alternate", false);
                    boolean option2 = getPrefs.getBoolean("white", false);
                    boolean option3 = getPrefs.getBoolean("standard",false);

                    if (blade.getAnimation() == null) {
                        // no animation, start it
                        if (option1 == true){
                            1stSound.start();
                            blade.startAnimation(animRotate);

                        } else if (option2 == true){
                            3rdSound.start();
                            blade.startAnimation(animRotate);

                        } else if (option3 == true) {
                            2ndFan.start();
                            blade.startAnimation(animRotate);

                        }

                        } else {
                            //animation is showing, stop it
                            blade.clearAnimation();
                            3rdSound.stop();
                            2ndSound.stop();
                            1stSound.stop();

                        }





                    current_image_index++;
                    current_image_index = current_image_index % images.length;
                    imgView.setImageResource(images[current_image_index]);
                    imgView.invalidate();


                }


            }
    );
}

1 个答案:

答案 0 :(得分:1)

看看MediaPlayer state diagram。致电stop()后,您还需要致电prepare()(或prepareAsync())以便再次播放。

简而言之,请执行以下操作:

3rdSound.stop();
3rdSound.prepareAsync();
2ndSound.stop();
2ndSound.prepareAsync();
1stSound.stop();
1stSound.prepareAsync();