按下按钮时播放声音 - Android

7

i have this code

package com.tct.soundTouch;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;

public class main extends Activity implements OnTouchListener {

    private MediaPlayer mp;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final Button zero = (Button) this.findViewById(R.id.button);
        zero.setOnTouchListener(this);

        mp = MediaPlayer.create(this, R.raw.sound);

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {

        case MotionEvent.ACTION_DOWN:
            mp.setLooping(true);
            mp.start();

        case MotionEvent.ACTION_UP:
            mp.pause();
        }

        return true;
    }

}

代码可以工作,但并不符合我的预期。声音会播放,但仅在我按下按钮的每一次时才会播放。我的想法是,当我按下按钮时,声音开始播放;当我停止操作(手指离开按钮)时,音乐暂停。

有任何想法吗?

谢谢。


2
只需在每个 case 后面添加 return true,现在就可以正常工作了。 - anvd
是的,或者使用break语句。两种方法都可以。 - Kevin Coppock
@Fel 如果那解决了您的问题,您应该将其发布为答案并接受它。 - Jason Plank
2个回答

3
这应该可以工作(我认为您的 switch-case 有些问题):
@Override
public boolean onTouch(View v, MotionEvent event) 
{   

    switch (event.getAction()) 
    {

    case MotionEvent.ACTION_DOWN:
    {
        mediaPlayer.setLooping(true);
        mediaPlayer.start();
    }

    break;
    case MotionEvent.ACTION_UP:
    {
        mediaPlayer.pause();
    }
    break;
}

return true;
}

0
public class MainActivity extends AppCompatActivity {

    Button button;
    MediaPlayer player;


    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );

        button = findViewById( R.id.Click );

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

                if (event.getAction()== MotionEvent.ACTION_DOWN) {
                    player= MediaPlayer.create( MainActivity.this,R.raw.horn );

                    player.start();
                }
                else if(event.getAction()==MotionEvent.ACTION_UP){
                    player.stop();
                    player.release();
                }
                return true;

            }
        } );

    }

}

请不要只是发布代码,尝试解释它。您是如何以及为什么更改它的。 - Frieder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接