Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 327
cyclingIsBetter Avatar asked Aug 07 '26 12:08

cyclingIsBetter


1 Answers

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.

like image 54
P.Melch Avatar answered Aug 09 '26 01:08

P.Melch