How to use touch listeners and play a sound only when touching a button?

android get touch coordinates in view
android touch event example
android track finger movement
android velocitytracker example
android pointer location source code
android touch event propagation
touch pointer android
button on touch listener android

I have an app with a button which plays a sound when clicked and pauses when clicked again. Now I want this button to only play sound when the button is touched and pause when the touch releases. What I mean is: I touch and hold it the song plays, I untouch it and the song stops playing.So the song should only play when the user touches and holds it not when the button is untouched. I even want a custom button(image) to show as long as the touch state is true and as soon as I untouch it, the default custom button is shown. Here is the code to my main activity:

package com.example.firozkaoo2222.myapplication;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

import static com.example.firozkaoo2222.myapplication.R.raw.police;

public class MainActivity extends AppCompatActivity {


private MediaPlayer policeSound;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button policeSounds = this.findViewById(R.id.police);

    policeSounds.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            int eventPadTouch = event.getAction();

            switch (eventPadTouch) {

                case MotionEvent.ACTION_DOWN:
                    // start playing sound , in your case:
                    policeSound.start();
                    return true;


                case MotionEvent.ACTION_UP:
                    // stop playing sound , in your case:
                    policeSound.stop();
                    return true;

            }
            return false;
        }
    });
}}

Code for my custom button.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:state_pressed="true"
    android:drawable="@drawable/button_pressed" />
<item
    android:drawable="@drawable/button_default" />


</selector>

Use this snippet instead of your OnClickListener method:

policeSounds.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

        if (policeSound == null) {
            policeSound = MediaPlayer.create(getApplicationContext(), R.raw.police);
        }

        int eventPadTouch = event.getAction();

        switch (eventPadTouch) {

            case MotionEvent.ACTION_DOWN:
                // start playing sound , in your case:
                policeSound.start();
                return true;


            case MotionEvent.ACTION_UP:
                // stop playing sound , in your case:
                policeSound.pause();
                return true;

        }
        return false;
    }
}

Handling touch and motion events, onTouchListener, Handles single touches for buttons, surfaces and more. onTouchEvent, A This listener is only designed for one button. // This means, no  2- sound effects : in the download file File Content Texting Sound Effect Touching (mobile screen) Sound Effect smartphone typing message on touch screen with haptic vibration Sound Effect Credit

If I understood you correctly, you need to use setOnTouchListener not setOnClickListener, and play the sound if event action is ACTION_DOWN (button is being pressed) and stop the sound when the event action is ACTION_UP (touch is released) :

yourButton.setOnTouchListener((v, event) -> {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                play();
                break;

            case MotionEvent.ACTION_UP:
                stop();
                break;

        }
        return false;
    });

Respond to touch events, Add a floating action button · Create shadows and clip views Use Google Play Billing with AIDL Setup a touch listener; Expose the rotation angle; Apply rotation The key to making your OpenGL ES application touch interactive is request that the renderer only redraw when the data changes using  How to Trigger an Event OnTouch on ROBLOX. Triggering an event when touching the part can be extremely effective to evoke emotions the game tries to deliver. This, however, should only be used when necessary.

Try adding this in your onCreate() method

policeSounds.setOnTouchListener(new View.OnTouchListener() {
                            @Override
                            public boolean onTouch(View v, MotionEvent event) {
                                if (event.getAction() == MotionEvent.ACTION_DOWN){ //The id check can be ignored since the listener is on the button already
                                    //play your sound
                                } else if (event.getAction() == MotionEvent.ACTION_UP){ //The id check can be ignored since the listener is on the button already
                                    //stop the sound
                                }
                                return true; //you need to return `true` otherwise it won't work
                            }
                        });

Track touch and pointer movements, Responding to media buttons · Handling changes in audio output · Managing This lesson describes how to track movement in touch events. A view in your app can request pointer capture only when the view hierarchy that contains it has focus. Whether you use a custom view or register a listener, your view receives a  The main reason to make your telephone voice sound pleasant is that (A) you can avoid straining your throat as you speak. (B) the other person may be angry, depressed, or bored. (C) you are applying good listening technique. (D) the other person has no visual cues to supplement your voice.

Play a Sound with Web Audio API, Play a Sound with Web Audio API is a tutorial that explains some common methods of The Mouse Event Listener “listens” for a signal from the mouse. click: The click event occurs when the pointing device button is clicked over an element. Of course, touchscreen devices make use of Touch Events. How to play sound with button click Android Studio How to Play a Sound File Using the MediaPlayer Class Button + sound = a good review: - Duration:

Call button action swift, You connect a button to your action method using the addTarget(_: action. The result is that an actionPerformed message is sent to all action listeners that are Dec 21, 2016 · Touch ID Authentication Tutorial for Swift 3. so it plays 24 hours a day, but the sound emerges from the speakers only when the timer says so. True, it would. Then again, to lower the volume, you could then just modify the system volume lower rather than moving the old files back. Thanks this thread helped me get keyboard sound after flashing custom rom, there was no setting adjust system volume in setting. 3rd party apps like volume plus did the trick.

Event handling · libgdx/libgdx Wiki · GitHub, Event handling is done using the common observer pattern. First we have to implement a listener interface called InputProcessor: touchDown(): Called when a finger went down on the screen or a mouse button was pressed. This event is only relevant on the desktop and will never occur on touch screen devices where  Starting with iOS 13, if you're listening to a new album or streaming a show and a friend or family member who also has AirPods wants to listen, use the new Audio Sharing feature. Have your friend

Comments
  • Could you please guide me exactly where I should put this code. I'm just a beginner
  • The app runs without any issue but when I touch the button the app closes.
  • just add if (policeSound == null) { policeSound = MediaPlayer.create(getApplicationContext(), R.raw.police); }
  • Awesome! Its working now. Just the button isn't changing.
  • It seems it's not related to java side, I think your xml file has some bugs
  • I got this concept ! Thanks :)
  • The app runs and upon pressing the button nothing actually happens. Remains stationary , button doesn't work.
  • It is still the same.Idk whats the issue