audio – How to play a Sound Effect in Android-ThrowExceptions

Exception or error:

I’m looking to do a very simple piece of code that plays a sound effect. So far I have this code:

SoundManager snd;
int combo;

private void soundSetup() {
    // Create an instance of the sound manger
    snd = new SoundManager(getApplicationContext());

    // Set volume rocker mode to media volume
    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);

    // Load the samples from res/raw
    combo = snd.load(R.raw.combo);
}

private void playSound() {
    soundSetup();
    snd.play(combo);
}

However, for some reason when I use the playSound() method, nothing happens. The audio file is in the correct location.

How to solve:

Is there a specific reason you are using SoundManager? I would use MediaPlayer instead, here is a link to the Android Docs

http://developer.android.com/reference/android/media/MediaPlayer.html

then it’s as simple as

    MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.combo);
    mp.start();

Make a directory called “raw/” under the “res/” directory. Drag wav or mp3 files into the raw/ directory. Play them from anywhere as above.

###

i have also attempted using the top answer, yet it resulted in NullPointerExceptions from the MediaPlayer when i tried playing a sound many times in a row, so I extended the code a bit.

FXPlayer is my global MediaPlayer.

public void playSound(int _id)
{
    if(FXPlayer != null)
    {
        FXPlayer.stop();
        FXPlayer.release();
    }
    FXPlayer = MediaPlayer.create(this, _id);
    if(FXPlayer != null)
        FXPlayer.start();
}

Leave a Reply

Your email address will not be published. Required fields are marked *