将声音注册到按钮单击

时间:2018-04-29 18:47:16

标签: java android

我希望能够按下按钮并在每次按下时播放声音。现在它只在第一次播放完毕后播放,而不是每次播放都播放。

公共类MainActivity扩展了AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    MediaPlayer boost = MediaPlayer.create(this, R.raw.boost);
    final Button button = findViewById(R.id.button_id);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!boost.isPlaying())
            {
                boost = new MediaPlayer();
            }
            try {
                AssetFileDescriptor afd = res.openRawResource(R.raw.boost);
                boost.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
                boost.prepare();
                boost.start();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    });
}

}

1 个答案:

答案 0 :(得分:0)

                if (!boost.isPlaying())
                        {
                            boost= new MediaPlayer();
                        }
                        try {
AssetFileDescriptor afd = res.openRawResourceFd(R.raw.boost);

                           boost.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
                            boost.prepare();
                            boost.start();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }