How can I make a sound overlap when pressing a button multiple times?

Bill Bai :

I'm new to Android java programming, but I've been programming Java by itself for a pretty long time. I've created a tiny app that will play a sound when a button is clicked. Ideally, when clicked, the button should play a sound which will play for its whole length, and when the button is clicked while the sound is still playing, it'll play the same sound overlapping the current sound. Although, in my app, when pressed while a sound is playing, it won't do anything and it will only play a sound when it is pressed after a sound is finished playing.

I've tried creating a new thread for sound.start() when pressed so it'll overlap like I'd like it to be, but I get an error when creating a thread for the sound (Cannot resolve symbol 'start').

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Button that is pressed to play the sound.
    imgBtn = findViewById(R.id.imageViewItm);

    // The sound that is played.
    final MediaPlayer sound = MediaPlayer.create(this, R.raw.sound_stuff);

    //Listener that will run the onClick() method when imgBtn is pressed.
    imgBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Plays sound
            sound.start();
        }
    });
}
Reaz Murshed :

I think creating a new MediaPlayer each time you are clicking the button should work fine. I have not tested the code yet. Let me know if you get an error.

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

    //Button that is pressed to play the sound.
    imgBtn = findViewById(R.id.imageViewItm);

    //Listener that will run the onClick() method when imgBtn is pressed.
    imgBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Plays sound
            MediaPlayer sound = MediaPlayer.create(MainActivity.this, R.raw.sound_stuff);
            sound.start();
        }
    });
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=141399&siteId=1