user1191027
user1191027

Reputation:

How to play a Sound Effect in Android

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.

Upvotes: 25

Views: 56418

Answers (2)

Ivo Robotnik
Ivo Robotnik

Reputation: 381

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();
}

Upvotes: 8

Sam Clewlow
Sam Clewlow

Reputation: 4351

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.

Upvotes: 72

Related Questions