按下按钮时想要播放随机声音

时间:2015-03-27 05:31:13

标签: android eclipse

我按下按钮时使用以下代码播放随机声音,但它显示我无法解决的错误。请有人帮忙:

 Button myButton = (Button)findViewById(R.id.button1);

        final List<Integer> soundList = new ArrayList<Integer>();
        soundList.add(R.raw.sound);
        soundList.add(R.raw.sound1);
        soundList.add(R.raw.sound2);
        soundList.add(R.raw.sound3);


       myButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
             playRandomSound();
        }

        private void playRandomSound() {
            // TODO Auto-generated method stub
            int randomInt = (new Random().nextInt(soundList.size()));
            int sound = soundList.get(randomInt);
            MediaPlayer mp = MediaPlayer.create(this, sound);
            mp.start();
        }
    });

错误:The method create(Context, int) in the type MediaPlayer is not applicable for the arguments (new View.OnClickListener(){}, int)

2 个答案:

答案 0 :(得分:2)

  

MediaPlayer类型中的方法create(Context,int)不是   适用于参数(new View.OnClickListener(){},int)

Activity上下文作为第一个参数传递给create方法:

MediaPlayer mp = MediaPlayer.create(myButton.getContext(), sound);

答案 1 :(得分:0)

您可以使用此功能。

final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);

其中&#34;这个&#34;是您活动的实例。然后在按钮调用的onCLickListener中

mp.start();