27

在我的 android 应用程序中,我有一些按钮,它们应该与onTouch()方法一起使用,当然当手指处于 ACTION_DOWN 位置时,我需要更改按钮的文本。但是这个按钮应该播放默认的 android 按钮点击声音(如 onClick() 方法)。我在哪里可以找到这样的声音?我想,它必须在 SDK 中,但我怎样才能找到它呢?什么方法更适合这种操作?我正在使用媒体播放器。

清单:

public boolean onTouch(View v, MotionEvent event) {
    int action = event.getAction();
    switch (action) {
    case MotionEvent.ACTION_DOWN:
        addTextShadow(v);
        Log.v(LOG_TAG, "ACTION_DOWN");
        break;
    case MotionEvent.ACTION_MOVE:
        clearTextShadow(v);
        isMoved = true;
        Log.v(LOG_TAG, "ACTION_MOVE");
        break;
    case MotionEvent.ACTION_UP:
        Log.v(LOG_TAG, "ACTION_UP");
        if (!isMoved) {
            clearTextShadow(v);
            if (v.getId() == R.id.btn_new) {
                Log.v(LOG_TAG, "New pressed");

                            playSound(); //MY METHOD TO PLAY SOUND

            } else if (v.getId() == R.id.btn_saved) {
                Log.v(LOG_TAG, "Saved pressed");
            } else if (v.getId() == R.id.btn_random) {
                Log.v(LOG_TAG, "Random pressed");
            }
        }
        isMoved = false;
        break;
    }
    return true;
}

还有我的 playSound() 方法:

    public void playSound(){
    if (mp != null) {
        mp.release();
        mp = null;
    }
    try {
        mp = MediaPlayer
    .create(MyActivity.this, R.raw.sound); //BUT HERE I NEED DEFAULT SOUND!
        mp.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
4

3 回答 3

78

在您的 onTouch() 方法中使用此代码:

view.playSoundEffect(android.view.SoundEffectConstants.CLICK);

If you are simply looking for a preset Android sound then it's better to use this functionality that's provided to you for free by the framework. Doing anything else, unless necessary for customization, would simply result in you working against the framework instead of working with it.

于 2012-08-11T19:51:42.763 回答
0

使用来自的默认声音/system/media/audio/

MediaPlayer 或 SoundPool 将有助于实现播放。

于 2012-08-11T15:52:47.917 回答
0

Consider using view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);.

It will do both: playing the default sound and vibrate if the user has it enabled in the global settings.

于 2016-01-29T10:42:51.777 回答