如何在Android应用程序中为onClick事件添加声音?

时间:2013-10-02 19:00:15

标签: android audio onclicklistener

我希望每当用户点击应用程序中的按钮时都能添加咔嗒声,有关如何使该行为适用于整个应用程序的任何建议? 干杯!

2 个答案:

答案 0 :(得分:3)

在按钮的onClick中,添加View.playSoundEffect(SoundEffectConstants.CLICK)

myButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            v.playSoundEffect(SoundEffectConstants.CLICK);
        }
    });

答案 1 :(得分:0)

或者您可以使用SoundPool进行更复杂的设置(例如,您可以设置左右音量值)

这只是一个例子:

private void playSound() {
        // TODO Auto-generated method stub      
        SoundPool pl = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
        // 5 indicates the maximum number of simultaneous streams for this SoundPool object

        int waterSound = pl.load(this, R.raw.water_sound_01, 0);
        // is the audio file I have imported in my project as resource

        pl.setOnLoadCompleteListener(new OnLoadCompleteListener() {             
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                // The onLoadComplet method is called when a sound has completed loading.
                // TODO Auto-generated method stub
                soundPool.play(sampleId, 1f, 1f, 0, 0, 1);
                // second and third parameters indicates left and right value (range = 0.0 to 1.0)
            }
        });
    }