28

I have a small (200kb) mp3 in the res/raw folder of my android app. I am trying to run it in an emulator from Eclipse. It is recognized as a resource in the R file but when I try to prepare/start, my activity crashes! Was there something else I needed to change, perhaps in the manifest?

MediaPlayer mPlayer = MediaPlayer.create(FakeCallScreen.this, R.raw.mysoundfile);

try {
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
// handle this later
}
damonkashu
  • 1,813
  • 5
  • 19
  • 25

3 Answers3

79

When starting the activity i.e on onCreate put the following code.

  public void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);         
        setContentView(R.layout.main);

        MediaPlayer mPlayer = MediaPlayer.create(FakeCallScreen.this, R.raw.mysoundfile);
        mPlayer.start();

    }

When stopping the activity i.e on onDestroy put the following code.

   public void onDestroy() {

    mPlayer.stop();
    super.onDestroy();

}

Hope it helps :)

Muhammad Shahab
  • 4,187
  • 4
  • 34
  • 44
9

You'll likely prefer to use the SoundPool class. It reduces latency when it's time to play the sound, and offers other niceties like being able to prioritise sounds when there are too many to play at once.

From the docs:

A SoundPool is a collection of samples that can be loaded into memory from a resource inside the APK or from a file in the file system. The SoundPool library uses the MediaPlayer service to decode the audio into a raw 16-bit PCM mono or stereo stream. This allows applications to ship with compressed streams without having to suffer the CPU load and latency of decompressing during playback.

For example:

/**
 * How many sounds can be played at once.
 */
private static final int MAX_SOUND_POOL_STREAMS = 4;

/**
 * Modify this as part of your own priority scheme. Higher numbers mean higher
 * priority. If you don't care, it's okay to use the same priority for every
 * sound.
 */
private static final int NORMAL_PRIORITY = 10;

private int mySoundId;

@Override
public void setupContent() {
    this.soundPool = new SoundPool(MAX_SOUND_POOL_STREAMS,
            AudioManager.STREAM_MUSIC, 100);
    this.mySoundId = this.soundPool.load(this.getApplicationContext(),
            R.raw.mySound, 1);
}

@Override
private void playMySound() {
    this.soundPool.play(this.mySoundId, 1, 1, NORMAL_PRIORITY, 0, 1);
}
Michael Scheper
  • 6,514
  • 7
  • 63
  • 76
  • Sound pool is for short duration sound (5 seconds) not for long musics or sounds. – Atif Mukhtiar Jul 07 '18 at 19:23
  • @AtifMukhtiar: Yep! Just the ticket for the 200KB MP3 mentioned in the question. – Michael Scheper Jul 08 '18 at 23:47
  • i have a sound of 174KB .ogg with 14 seconds. But the sound plays for 5 seconds that sound is created with 44KHz. Then i created a sound with 16KHz i was able to play for 10 seconds. – Atif Mukhtiar Jul 09 '18 at 08:04
  • Sorry it's not working out for you. It looks like there's a 1MB buffer limit. I imagine that would apply to the sound after it has been uncompressed from MP3 or OGG. https://stackoverflow.com/questions/13377604/soundpool-plays-only-first-5-secs-of-file-why – Michael Scheper Jul 12 '18 at 14:38
3

this is a static method I use in my projects. I add it to my Utils class:

    public static void playSound(final Context context, final SoundType type)
    {

            new Thread(new Runnable()
            {

                @Override
                public void run()
                {
                    MediaPlayer mediaPlayer = new MediaPlayer();
                    int resId = -1;
                    switch (type)
                    {
                    case INCOMING_NOTIFICATION:
                        resId=R.raw.noti_sound;
                        break;
                    case SEND_BETTING_SLIP:
                        resId=R.raw.slip_sent;
                        break;
                    case TRIVIA_RIGHT_ANSWER:
                        resId=R.raw.game_bonus;
                        break;
                    case TRIVIA_WRONG_ANSWER:
                        resId=R.raw.whistle_referee_trivia_bad_answer;
                        break;
                    }

                    if (resId != -1)
                    {
                        mediaPlayer = MediaPlayer.create(context, resId);
                        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        mediaPlayer.setLooping(false);
                        mediaPlayer.start();

                        while (mediaPlayer.isPlaying() == true)
                        {
                        }
                    }
                }
            }).start();

        }
}

now I defind an Enum (SoundType) and placed the mp3 files in raw folder under res folder.

Gal Rom
  • 6,221
  • 3
  • 41
  • 33