按下按钮时播放声音 - 机器人

时间:2011-03-09 23:00:51

标签: java android ontouchlistener

我有这个代码

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 个答案:

答案 0 :(得分:3)

这应该有效(我认为你的交换机案例有问题):

@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;
}

答案 1 :(得分: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;

            }
        } );

    }

}