Asaf Nevo
Asaf Nevo

Reputation: 11688

to play sound for my android application

I'm trying to load a sound effect which plays when a specific event happens.

For some reason I can hear the sound but it doesn't play the whole file and it brakes it in the middle.

My sound code:

public class SoundManager {

    private Context context;
    private int nudgeSound = R.raw.nudge;


    public SoundManager(Context context)
    {
        this.context = context;
    }

    public void playNudgeSound()
    {           
        final MediaPlayer mediaPlayer = MediaPlayer.create(context, nudgeSound);

          mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

              @Override
              public void onCompletion(MediaPlayer mp) {
                  mediaPlayer.reset();
              }

          });   
          mediaPlayer.start();

    }
}

my initialization:

    SoundManager soundManager = new SoundManager(this);
    soundManager.playNudgeSound();

Upvotes: 1

Views: 1383

Answers (2)

Asaf Nevo
Asaf Nevo

Reputation: 11688

Ok after few days of wondering around and lots of frustration i've found out that my problem was that the MediaPlayer.create() didn't had much time to load the file to memory... it happened because create() and start() were called almost at the same time..

my recommendation is to load all your sound files when your Application is loading, and just call start() whenever you need them. build some kind of SoundManager class.

Thanks everyone ! hope it will help someone!

Upvotes: 3

Mark
Mark

Reputation: 7625

Have you ever considered to use a SoundPool instead?! In my applications this works fine.

AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);

SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_NOTIFICATION, 0);
int sound = soundPool.load(context, R.raw.beep, 1);
soundPool.play(sound, maxVolume, maxVolume, 1, 0, 1f);

Upvotes: 2

Related Questions