Christian Waldmann
Christian Waldmann

Reputation: 94

Android: Efficent Way of playing Sounds

Here is my code, it's easier to show it to you and then explain:

public class Sound {
    public MediaPlayer audio;

    public Sound(Context context, int id) {
        audio = MediaPlayer.create(context.getApplicationContext(), id);
    }
}

public class ClassA {
    Sound sound = new Sound(getContext(), R.raw.audio);

    public void method() {
        //plays only once here, so its not looping, which is good
        sound.audio.start();
    }
}

So what I'm trying to do here is have a class that defines a sound, and then allows me to play it, but when I load up my app on my phone, it crashes.

I just started working with sounds today so I don't know much about. I don't know why this doesn't work, and I planned on releasing my first app today.
Your help would be much appreciated!

Forgot to mention, the reason I'm doing this is so that my games sound doesn't crash due to creating many MediaPlayers.

Upvotes: 0

Views: 61

Answers (1)

Fred Felsbruckner
Fred Felsbruckner

Reputation: 88

For short sound samples it is better to use android.media.SoundPool.

import android.content.Context;
import android.media.*;

anywhere in your Activity

AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
SoundPool soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
int soundId = soundPool.load(theContext, R.raw.audio, 1);
int streamVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int streamId = soundPool.play(soundId, streamVolume, streamVolume, 1, 0, 1f);

Upvotes: 1

Related Questions