Search code examples
javaandroidxmlaudiomp3

How to make audio play on first click?


I have two problems.

  1. The first time I click the ImageView, the audio doesn't play. Only when I click the ImageView a second time the audio plays. What do i have to change or add to my code in order to make the audio play on the very first click?

  2. When I click the ImageView again after already starting the audio, I have to wait for the audio to finish if I want to play it again. What do I have to add to my code in order to restart the audio with each click even if the audio is playing?

The code:

public void next (View view){

    ImageView one = (ImageView)this.findViewById(R.id.Seethrough);
    final MediaPlayer mp = MediaPlayer.create(this, R.raw.dry);
    one.setOnClickListener(new View.OnClickListener(){

        public void onClick(View v) {
            mp.start();
        }
    });
}

<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"
    />

Solution

  • You set the android:onClick in the xml attribute which will invoke your next method, and you setOnClickListener again in your next, so the first time you click the imageView, the mp.start() will not be invoked.

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