有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我想做的是在这个按钮上点击三种声音中的一种。声音在首选项屏幕中。在按钮上单击它也应该显示动画。目前正在发生的是,我将点击按钮,一切都将完美地工作,但我停止动画和声音,我第二次点击按钮。当我再次单击按钮开始备份动画和声音时,我听不到声音,但动画仍然有效。我真的不知道怎么了。这是我的密码

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) 个答案

  1. # 1 楼答案

    看看MediaPlayer state diagram。在调用stop()之后,还需要调用prepare()(或prepareAsync())才能再次播放

    简而言之,要做到:

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