Search code examples
javaandroidonclickplaysound

How to make a button play a sound as it launches another activity when pressed?


Current code:

   MediaPlayer mp;

    button1=(ImageButton)findViewById(R.id.button1);
    button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i = new Intent(getApplicationContext(), Activity1.class);
            startActivity(i);
        }

    });

So how would a button start a new activity and play a sound while doing so?

What I've tried: various methods like playSound( ); in the method.

It only plays the default android sound. I want a specific sound stored in the raw directory. So when the button get's pressed it launches both the intent to launch the activity as well as the specific sound.

Error:

When I try to put MediaPlayer mp; above the button, it states variable mp is already defined. I just need someone to append the activity launch code so that it will play the sound as well.


Solution

  • First you need to put a sound.mp3 in raw folder
    MediaPlayer mp;

    button1=(ImageButton)findViewById(R.id.button1);
    button1.setOnClickListener(new View.OnClickListener() {
    
        @Override
        public void onClick(View v) {
            try {
                        mp = MediaPlayer.create(Music.this, R.raw.sound);
                    } catch (IllegalArgumentException e) {
                        Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                    } catch (SecurityException e) {
                        Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                    } catch (IllegalStateException e) {
                        Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                    }
                    try {
                        mp.prepare();
                    } catch (IllegalStateException e) {
                        Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                    } catch (IOException e) {
                        Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                    }
                    mp.start();
            Intent i = new Intent(getApplicationContext(), Activity1.class);
            startActivity(i);
        }
    
    });