如何使用view.playSoundEffect(SoundEffectConstants.CLICK)使用默认的单击声音;

时间:2012-12-03 09:15:34

标签: android android-mediaplayer

我想使用默认的TICK声音,但我不知道如何或在何处放置此代码

view.playSoundEffect(SoundEffectConstants.CLICK);

我在另一篇文章中找到了这段代码。

这是我的代码:

        protected void onCreate(Bundle savedInstanceState)
        {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final MediaPlayer mp = MediaPlayer.create(this, R.raw.blah);

        Button Button01 = (Button)this.findViewById(R.id.Button01);
        Button01.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {
                mp.start();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    public void onClick(View v){}

    public void disclaimerBTN (View v){
        Toast.makeText(this, "FAILED:      The remote object is " +
                            "not responding to this command",Toast.LENGTH_LONG).show();
    }
}

那我在哪里放view.play .....代码? 非常感谢。

2 个答案:

答案 0 :(得分:7)

要在按钮点击事件中使用AudioManager.playSoundEffect,您可以尝试:

AudioManager audioManager = 
            (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);

 Button01.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {
                 audioManager.playSoundEffect(SoundEffectConstants.CLICK);   
                 //mp.start();
            }
        });

供参考,您可以在Google源代码中看到此示例:

http://code.google.com/p/android-traditional-chinese-ime/source/browse/trunk/src/com/googlecode/tcime/SoundMotionEffect.java?r=13

答案 1 :(得分:2)

您可以通过以下方式调用来播放每个视图中的声音:

Button01.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {
                 v.playSoundEffect(SoundEffectConstants.CLICK);   
            }
        });

请注意,如果默认情况下触控声音关闭,声音将无法播放。这是在常规设备声音首选项中设置的(设置 - >声音 - >声音或更新的操作系统:选项>声音>触摸)

此外,如果设置了此设置,大多数点击事件都会触发点击声音!