Search code examples
androidmedia-playeroggplaysound

Android - Play sound in a class File?


I can play a sound in my activity. e.g.:

public class APP extends Activity {

MediaPlayer btnClick;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

btnClick = MediaPlayer.create(this, R.raw.button_click);

    }

... on Button Click play sound ...
btnClick.start();
...

}

But I have no idea how to play a sound in a class file?

public class test {
...
}

Is that not possible? I tried so many variations. In the class file, I can't play a sound.


Solution

  • You will have to forward your Context to the class in the constructor.

    Add a class member for your Context:

    Context mContext;
    

    Then, add a constructor that takes a Context:

    public test (Context c){
       mContext = c;
    } 
    

    Instantiate your class using this constructor:

    Test test = new Test(this); //Assuming you call this in an Activity
    

    Lastly, where you want to play your sound in your class, use mContext as the Context:

    MediaPlayer mp = MediaPlayer.create(mContext, R.raw.button_click);
    

    If you want to instantiate your class in a FrameLayout, use this code:

    Test test = new Test(getContext()); //Assuming you call this in a subclass of FrameLayout