3

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?

cyclingIsBetter
  • 17,447
  • 50
  • 156
  • 241

2 Answers2

12

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.

P.Melch
  • 8,066
  • 43
  • 40
  • Audio is not an activity, it's a separate class that I use to manage audio, in fact I pass Audio.this – cyclingIsBetter Aug 28 '12 at 07:57
  • Late answer: you need an Android Context to pass. not your Audio class. So either add a Context parameter to the playClick method or have each Activity have their own instance of the Audio class with the Activity Context passed in the constructor. – P.Melch Jul 24 '18 at 08:58
  • can anyone tell me how can i add 2 raw files in mediaplayer.create – Vasant Raval Feb 03 '22 at 04:48
  • If you want to play two sounds in parallel you have to create two MediaPlayers – P.Melch Feb 04 '22 at 07:40
1
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();
Alexis C.
  • 91,686
  • 21
  • 171
  • 177