user5379539
user5379539

Reputation:

How to start audio as soon as ImageView is pressed?

My code only plays the audio when the ImageView is released. What should I add in order to make the audio start as soon as it is pressed?

MediaPlayer mp = null;

public void next (View view) {
    if (mp != null) {
        mp.stop();
        mp.release();
    }
    mp = MediaPlayer.create(this, R.raw.dry);
    mp.start();
}

XML code:

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/seethrough"
    android:clickable="true"
    android:id="@+id/Seethrough"
    android:onClick="next"
    />

Upvotes: 1

Views: 56

Answers (2)

Lincoln White
Lincoln White

Reputation: 649

Copy and paste this and it should be working!

ImageView seethrough;    

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
seethrough = (ImageView) findViewById(R.id.Seethrough);
seethrough.setOnTouchListener(this);
}

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

    ImageView view = (ImageView) v;
switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                 if (mp != null) {
                 mp.stop();
                 mp.release();
                 }
                 mp = MediaPlayer.create(this, R.raw.dry);
                 mp.start();
                    break;
                case MotionEvent.ACTION_MOVE:
                    break;
                case MotionEvent.ACTION_UP:
                    break;
                case MotionEvent.ACTION_CANCEL:
                    break;
            }
    return true;
}

Upvotes: 0

Abhiram mishra
Abhiram mishra

Reputation: 1617

You should use something like below

ImageView seethrough= (ImageView)this.findViewById(R.id.Seethrough);
seethrough.setOnTouchListener(new OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            if (event.getAction() == MotionEvent.ACTION_DOWN)
                // this is where you should call next()
            else if (event.getAction() == MotionEvent.ACTION_UP)
                  // this is if you are interested in the release action 
            return false;
        }
    });

Upvotes: 1

Related Questions