Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play a Sound Effect in Android

Tags:

android

audio

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.

like image 351
ThreaT Avatar asked May 04 '12 14:05

ThreaT


People also ask

How do I add sounds to my android?

Steps to add your audio to your Android Studio projectCreate a new folder named "raw" in your Android project's "res" folder and place your audio file inside the "raw" folder. You can see the audio is now successfully added into your Android Studio project by viewing the "raw" subfolder under "res" folder.


2 Answers

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.

like image 170
Sam Clewlow Avatar answered Oct 19 '22 21:10

Sam Clewlow


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();
}
like image 33
Ivo Robotnik Avatar answered Oct 19 '22 20:10

Ivo Robotnik