Playing random sound effect on each click

All your problems with Audio, Video and Images.

Playing random sound effect on each click

Postby Roo » Wed Mar 02, 2011 11:23 pm

I have a button and on each click I want a different sound to play. I need some help getting the second sound to work. I want the two Finn sound clips to be played when button 1 is pressed. Here's my code so far:
Code: Select all
package com.andrew.finnandjake;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Sounds extends Activity {
private SoundManager mSoundManager;

/** Called when the activity is first created. */

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mSoundManager = new SoundManager();
    mSoundManager.initSounds(getBaseContext());
    mSoundManager.addSound(1, R.raw.finn_whatthejugisthat);
    mSoundManager.addSound(2, R.raw.jake_dancingwithbabes);
    mSoundManager.addSound(3, R.raw.lsp_dontlumpingyellatme);
    mSoundManager.addSound(4, R.raw.pb_shouldntpunchbrainiacs);
    mSoundManager.addSound(5, R.raw.iceking_imabanana);
    mSoundManager.addSound(6, R.raw.finn_wordtoyourmother);



    Button b1 = (Button)findViewById(R.id.Button1);
    b1.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            mSoundManager.playSound(1, 0);

        }
    });

    Button b2 = (Button)findViewById(R.id.Button2);
    b2.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mSoundManager.playSound(2, 0);
        }
    });
   
    Button b3 = (Button)findViewById(R.id.Button3);
    b3.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mSoundManager.playSound(3, 0);
        }
    });
   
    Button b4 = (Button)findViewById(R.id.Button4);
    b4.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mSoundManager.playSound(4, 0);
        }
    });
   
    Button b5 = (Button)findViewById(R.id.Button5);
    b5.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            mSoundManager.playSound(5, 0);
        }
    });
   
}
}
Roo
Junior Developer
Junior Developer
 
Posts: 11
Joined: Wed Aug 11, 2010 10:43 am

Top

Re: Playing random sound effect on each click

Postby Shattered9 » Thu Mar 03, 2011 7:27 pm

This shouldn't be too difficult depending on how elegant you want your code to be.

The first step, at least in the easy way of doing things, is to have all of the sounds for each character in chronological order. The most efficient (As far as typing in and not having to change it over and over) way to do this is to think about the max sounds each character would have, and simply skip that many from the first sound of that character to the first of the next. So say you wanted a max of ten sounds per character it could be something like :

Code: Select all
mSoundManager.addSound(1, R.raw.finn_whatthejugisthat);
    mSoundManager.addSound(2, R.raw.finn_wordtoyourmother);
    mSoundManager.addSound(11, R.raw.jake_dancingwithbabes);
    mSoundManager.addSound(12, R.raw.jake_sayinsomethingrandom);
    mSoundManager.addSound(13, R.raw.jake_sayinsomethingelserandom);
    mSoundManager.addSound(21, R.raw.lsp_dontlumpingyellatme);
    mSoundManager.addSound(31, R.raw.pb_shouldntpunchbrainiacs);
    mSoundManager.addSound(41, R.raw.iceking_imabanana);


Etc. This is of course without knowing what exactly that "SoundManager" class is, so I'm not sure if that would create unnecessary unused sounds in the blank spaces or something, but I wouldn't imagine so.

Then you can create an object of Java's Random class, use that to generate a random number up to the max number of sounds that character has minus one and add it onto the lowest number that character starts at. This will give you a randomly chosen number in that characters range, which you can stick into a variable and use to call the sound. I suppose it would look something like this for say, Jake, at least in my example with the two extra fake sounds.

Code: Select all
   private Random random = new Random();


        Button b2 = (Button)findViewById(R.id.Button2);
        b2.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
               int rndNum = random.nextInt(2);
               int soundNum = 11 + rndNum;
                mSoundManager.playSound(soundNum, 0);

            }
        });


Creating the Random object should obviously be done once at the top and not before every onClick block, but I put it there for clarity. Ideally the values like 2 in the random number generator and 11 would instead be held in instance variables, rather than having them coded straight in.

Of course, ideally you would do things a little more elaborate than this. This is simply the most basic way I could think of to try and do it. Unfortunately I can't do any code tests or anything at the moment, but I believe what I said here should work. If you have any problems with it or just don't like the non-elegant way I suggested I will try to help you out more when I can actually code tests and what not.
Last edited by Shattered9 on Mon Mar 07, 2011 3:50 pm, edited 1 time in total.
Shattered9
Developer
Developer
 
Posts: 39
Joined: Sat Feb 12, 2011 4:41 pm

Re: Playing random sound effect on each click

Postby Roo » Sun Mar 06, 2011 2:24 am

Shattered9 wrote:
Code: Select all
   private Random random = new Random();


        Button b2 = (Button)findViewById(R.id.Button2);
        b2.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
               int rndNum = random.nextInt(2);
               int soundNum = 11 + rndNum;
                mSoundManager.playSound(soundNum, 0);

            }
        });




I tried what you suggested, but the button would only play the initial sound. It wouldn't generate a random one from the list . I understand everything you said, but I just don't know the Java very well. I'll keep trying to figure this out in the mean time, but if you can help me out that would AWESOME. This is literally the only thing keeping me from finishing this app. Also, here's Sound Manager:
Code: Select all
package com.andrew.finnandjake;

import java.util.HashMap;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;


public class SoundManager {
   
   static private SoundManager _instance;
   private static SoundPool mSoundPool;
   private static HashMap<Integer, Integer> mSoundPoolMap;
   private static AudioManager  mAudioManager;
   private static Context mContext;
   
   SoundManager()
   {   
   }
   
   /**
    * Requests the instance of the Sound Manager and creates it
    * if it does not exist.
    *
    * @return Returns the single instance of the SoundManager
    */
   static synchronized public SoundManager getInstance()
   {
       if (_instance == null)
         _instance = new SoundManager();
       return _instance;
    }
   
   /**
    * Initialises the storage for the sounds
    *
    * @param theContext The Application context
    */
   public static  void initSounds(Context theContext)
   {
       mContext = theContext;
        mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
        mSoundPoolMap = new HashMap<Integer, Integer>();
        mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);       
   }
   
   /**
    * Add a new Sound to the SoundPool
    *
    * @param Index - The Sound Index for Retrieval
    * @param SoundID - The Android ID for the Sound asset.
    */
   public static void addSound(int Index,int SoundID)
   {
      mSoundPoolMap.put(Index, mSoundPool.load(mContext, SoundID, 1));
   }
   
   /**
    * Loads the various sound assets
    * Currently hardcoded but could easily be changed to be flexible.
    */
   public static void loadSounds()
   {
      mSoundPoolMap.put(1, mSoundPool.load(mContext, R.raw.finn_wordtoyourmother, 1));
      mSoundPoolMap.put(2, mSoundPool.load(mContext, R.raw.finn_whatthejugisthat, 1));      
   }
   
   /**
    * Plays a Sound
    *
    * @param index - The Index of the Sound to be played
    * @param speed - The Speed to play not, not currently used but included for compatibility
    */
   public static void playSound(int index,float speed)
   {       
           float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
           streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
           mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, speed);
   }
   
   /**
    * Stop a Sound
    * @param index - index of the sound to be stopped
    */
   public static void stopSound(int index)
   {
      mSoundPool.stop(mSoundPoolMap.get(index));
   }
   
   public static void cleanup()
   {
      mSoundPool.release();
      mSoundPool = null;
       mSoundPoolMap.clear();
       mAudioManager.unloadSoundEffects();
       _instance = null;
      
   }

   
}
Roo
Junior Developer
Junior Developer
 
Posts: 11
Joined: Wed Aug 11, 2010 10:43 am

Re: Playing random sound effect on each click

Postby Shattered9 » Mon Mar 07, 2011 4:10 pm

It plays that one sound every time you hit the button? That would mean that it isn't being given a proper random number. Try sending the number that you are giving mSoundManager to your log and see what it returns. If that is actually giving you a random number, then something is either a little off in the way you defined your resources or somewhere in your code it is telling that button to play that specific sound.

If you're having problems figuring it out, try just passing mSoundManager the number of one of the other sounds flat out, which would still logically be playing that first sound. Then you can back track and try to find the issue without worrying about the random component of it.
Shattered9
Developer
Developer
 
Posts: 39
Joined: Sat Feb 12, 2011 4:41 pm

Re: Playing random sound effect on each click

Postby sebjeri » Thu Mar 31, 2011 3:33 am

Hi, I'm a started, looking for coding help for an image gallery with a small narration (audio file) will be played when clicked on every image. Any help will be greately appreciated. image and audio should have same file names in the drawable folder. Thanks - Jeri
sebjeri
Freshman
Freshman
 
Posts: 2
Joined: Thu Mar 31, 2011 3:20 am

Re: Playing random sound effect on each click

Postby strider2023 » Fri Apr 01, 2011 9:26 am

Hi Jeri,

First thing always keep your sound files in your "raw" folder. Second on image selection you can play your sound. Example:

imagegallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
if(position == 1) {
//play sound 1
}
//...... and so on
}
});
strider2023
Senior Developer
Senior Developer
 
Posts: 126
Joined: Tue Mar 02, 2010 6:34 am
Location: Chennai, India

Top

Return to Multimedia Problems

Who is online

Users browsing this forum: No registered users and 19 guests