Search code examples
javaandroidsoundpool

Selecting a Sound in an activity to be played in another activity


I have this idea that I couldn't code so I'm here Asking for help

I have two activities the first one : Xml file : Button Java File : a click listener for the Button to play a sound effect with the SoundPool class from res/raw

--all simple--

what want to do is to create a second activity where the user can choose an other sound effects like Sound1 or Sound2 ...etc from a radio button group, to be played instead.

this was my idea, so please help me coding this I'm stuck since 2 weeks and I have 0 clue whats the next step.

SOS =)


Solution

  • You could define a global variable for the sound effect to play:

    int activeSoundEffectRawId = R.raw.defaultSound;
    

    And play it with your SoundPool's load method.

    To select the sound to play, you could add another button to your xml file that starts Activity2:

    Button btnSelectSound = (Button) findViewById (R.id.button2);
    btnSelectSound.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivityForResult(new Intent(Activity1.this, Activity2.class), 1000);
        }
    });
    

    It's important that you start the activity for result here with the request code 1000 (this number can be changed for sure).

    In your Activity 2 you need the logic to select your sound and for example a "OK" button to save the selection. That ok button will hand over the selected sound to Activity1:

    Button btnOk = (Button) findViewById (R.id.ok);
    btnOk.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent returnIntent = new Intent();
            returnIntent.putExtra("soundRawId", selectedSoundRawId /* <- replace this with the selected sound, like R.raw.yourSound */);
            setResult(Activity.RESULT_OK,returnIntent);
            finish();
        }
    });
    

    After that, you can set the selected sound in Activity1:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000 && resultCode == Activity.RESULT_OK) {
            selectedSoundRawId = data.getIntExtra("soundRawId");
        }
    }