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

}

and it works but not as i expected. The sound plays but only for each time that i press the button. My idea is. While i press the button the sound plays, when i stop the action (finger out of the button) music pause.

Any idea please?

thanks

anvd
  • 3,997
  • 19
  • 65
  • 126

2 Answers2

3

This should work (there was something wrong with your switch-cases I think):

@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;
}
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Balázs Édes
  • 13,452
  • 6
  • 54
  • 89
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;

            }
        } );

    }

}
robsiemb
  • 6,157
  • 7
  • 32
  • 46