简体   繁体   中英

App stops unexpectedly when using OnTouchListener, MotionEvent.ACTION_UP

So I want to create buttons that play music as long as it is pressed, but once it is released, the music stops.

In my createListeners() , I have the following:

b1.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN) {
                startBeat(1, m1);
                return true;
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                m1.stop();
            }
            return false;
        }
    });

m1 is a MediaPlayer , and in the method startBeat , m1.start() has been called.

When running the app, the music plays fine, as long as I don't release the button. However, the moment I release the button, the app says it stopped unexpectedly. What could be causing this problem?

Is there another way I could go about implementing this feature?

Maybe you try play again the MediaPlayer ??

Calling stop() stops playback and causes a MediaPlayer in the Started, Paused, Prepared or PlaybackCompleted state to enter the Stopped state. Once in the Stopped state, playback cannot be started until prepare() or prepareAsync() are called to set the MediaPlayer object to the Prepared state again.

If you don't, try m1.pause(); and m1.seekTo(0) to simulate the stop...

public boolean onTouch(View v, MotionEvent event) {
    if(event.getAction() == MotionEvent.ACTION_DOWN) {
        startBeat(1, m1);
        return true;
    } else if (event.getAction() == MotionEvent.ACTION_UP) {
        m1.pause();
        m1.seekTo(0);
        return true;
    }
    return false;
}

EDIT: I found out what I was doing wrong. I was initializing and starting the MediaPlayer in my startBeat method, and stopping the player in the onTouch method. Once I moved it all into onTouch, it worked. So I guess something weird was happening before. Thanks for the answers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM