cyclingIsBetter
cyclingIsBetter

Reputation: 17591

Android: mediaplayer create

I have this code:

package com.example.pr;

import android.media.MediaPlayer;

public class Audio{

    MediaPlayer mp;

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

I have an error in "create" with this message "The method create(Context, int) in the type MediaPlayer is not applicable for the arguments (Audio, int)"

why?

Upvotes: 3

Views: 41220

Answers (2)

P.Melch
P.Melch

Reputation: 8180

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 don't forget to call release on the MediaPlayer instance once the sound has finished, or you'll get an exception.

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

Upvotes: 12

Alexis C.
Alexis C.

Reputation: 93842

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();

Upvotes: 1

Related Questions