Android: mediaplayer create

Android: mediaplayer create

MediaPlayer.create() needs a Context as first parameter. Pass in the current Activity and it should work.

try:

public void playClick(Context context){
    mp = MediaPlayer.create(context, R.raw.click);  
    mp.start();
}

in your Activity:

audio = new Audio();
...
audio.playClick(this);

but dont forget to call release on the MediaPlayer instance once the sound has finished, or youll get an exception.

However, for playing short clicks using a SoundPool might be better anyway.

public class Audio{

    MediaPlayer mp;
Context context;

     public Audio(Context ct){
     this.context = ct;
}
    public void playClick(){
        mp = MediaPlayer.create(context, R.raw.click);  
        mp.prepare();
        mp.start();
    }

From your Activity:

Audio audio = new Audio(YourActivity.getApplicationContext());
audio.playClick();

Android: mediaplayer create

Leave a Reply

Your email address will not be published.