Search code examples
androidaudiorandombackgroundmp3

Android Random Background Image with background sound


I have an Activity that if opened, it displays random background.

I was wondering if having a background with sound is possible in android. Like if the background is Nature.jpg then the background audio is BirdsChirping.mp3. (So it matches the ambiance of the background.)

Like this:

> Nature.jpg = BirdsChirping.mp3 
> Ocean.jpg = Waves.mp3 
> Plane.jpg = JetEngineSound.mp3

Here is my current code:

//  RANDOM IMAGE
    int[] photos={R.drawable.nature, R.drawable.ocean};
    ImageView image= (ImageView) findViewById(R.id.main_activity_bg);
    Random ran=new Random();
    int i=ran.nextInt(photos.length);
    image.setImageResource(photos[i]);

Solution

  • First, put your mp3 files in a directory called raw then create an array named sounds with all your mp3 files IDs. This array's size should be the same size of the photos array and also be the same order so that the first file of photos array is correspondent with the first file of sounds array like the following code:

    int[] photos={R.drawable.nature, R.drawable.ocean};
    int[] sounds={R.raw.BirdsChirping, R.raw.Waves};
    

    Then to play a sound you need to use MediaPlayer

    final MediaPlayer mp = MediaPlayer.create(this, sounds[i]);
    

    This is how to initialize a MediaPlayer. The MediaPlayer follows the Static Factory Method Design Pattern. To get an instance, we call its create() method and pass it the context and the resource Id of the sound we want to play.

    mp.start();
    

    To play the sound, we call MediaPlayer's start() method. This method starts the playback of the sound.

        int[] photos={R.drawable.nature, R.drawable.ocean};
            int[] sounds={R.raw.BirdsChirping, R.raw.Waves};
            ImageView image= (ImageView) findViewById(R.id.main_activity_bg);
            Random ran=new Random();
            int i=ran.nextInt(photos.length);
            image.setImageResource(photos[i]);
    final MediaPlayer mp = MediaPlayer.create(this, sounds[i]);
            mp.start();
    

    This is how your full code should be for playing a certain sound when a certain photo was set randomly in the background.