简体   繁体   English

使用OnTouchListener,MotionEvent.ACTION_UP时,应用程序意外停止

[英]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: 在我的createListeners() ,我具有以下内容:

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. m1MediaPlayer ,在方法startBeat ,已调用m1.start()

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 ?? 也许您尝试再次MediaPlayer

Calling stop() stops playback and causes a MediaPlayer in the Started, Paused, Prepared or PlaybackCompleted state to enter the Stopped state. 调用stop()会停止播放,并使处于Started,Paused,Prepared或PlaybackCompleted状态的MediaPlayer进入Stopped状态。 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. 一旦处于“已停止”状态, 就无法开始播放,直到调用prepare()或prepareAsync()将MediaPlayer对象再次设置为Prepared状态。

If you don't, try m1.pause(); 如果不这样做,请尝试m1.pause(); and m1.seekTo(0) to simulate the stop... m1.seekTo(0)模拟停止...

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. 我正在用startBeat方法初始化并启动MediaPlayer,并在onTouch方法中停止播放器。 Once I moved it all into onTouch, it worked. 一旦将它们全部移到onTouch,它就可以工作了。 So I guess something weird was happening before. 所以我想以前发生了一些奇怪的事情。 Thanks for the answers! 感谢您的回答!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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