Play A Random Sound onTouch

瘦欲@ 提交于 2019-12-12 04:58:24

问题


I'm trying to play a random sound onTouch event (currently working), but the sound is actually played twice onTouch event instead of once as intended. I'm assuming this is due to the UP and Down onTouch event. Any thoughts?

NOTE: I commented out the additional random sound files while testing.

package com.tmapps.wiub;

import java.util.Random;
import com.tmapps.wiub.SoundManager;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;

public class Soundboard extends Activity {
    private SoundManager mSoundManager;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // FULLSCREEN CODE
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.main);

        mSoundManager = new SoundManager();
        mSoundManager.initSounds(getBaseContext());
        mSoundManager.addSound(0, R.raw.sound0);

     // COMMENTED OUT WHILE TESTING  
     // mSoundManager.addSound(1, R.raw.sound1);
     // mSoundManager.addSound(2, R.raw.sound2);
     // mSoundManager.addSound(3, R.raw.sound3);
     // mSoundManager.addSound(4, R.raw.sound4);
     // mSoundManager.addSound(5, R.raw.sound5);
     // mSoundManager.addSound(6, R.raw.sound6);
     // mSoundManager.addSound(7, R.raw.sound7);
     // mSoundManager.addSound(8, R.raw.sound8);
     // mSoundManager.addSound(9, R.raw.sound9);

    };

        Random r = new Random();
        int x = r.nextInt(1);

        switch (evt.getAction()) 
        {
            case MotionEvent.ACTION_DOWN:
            mSoundManager.playSound(x);
            return super.onTouchEvent(evt);

            case MotionEvent.ACTION_UP:
            break;
            default:
            break;
        }

回答1:


that is because both ACTION_DOWN and ACTION_UP are firing, implement on code only on one of them

    public boolean onTouchEvent(MotionEvent evt) 
    {
        switch (evt.getAction()) 
        {
            case MotionEvent.ACTION_DOWN: 
            break;
            case MotionEvent.ACTION_UP:
            break;
            default:
            break;
        }
        return true;
    }


来源:https://stackoverflow.com/questions/10115238/play-a-random-sound-ontouch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!