سؤال

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.

هل كانت مفيدة؟

المحلول 2

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

نصائح أخرى

You can only specify mediaPlayer in the test class and then call the method from test class which involves the mediaPlayerSettings. Test class itself can't play because it doesn't extend activity.

But if you want to get the method from class test do it like that:

public class test
{

    private static MediaPlayer mp;

    public static void startPlayingSound(Context con)
       {
         mp= MediaPlayer.create(con, R.raw.sound);
         mp.start();
       }

//and to stop it use this method below

    public static void stopPlayingSound(Context con)
      { 
       if(!mp.isPlaying())
         {
           mp.release();
           mp = null;
         }
     }

}

Consequently in the Activity call it like that:

//for start
test.startPlayingSound(this);
//and for stop
test.stopPlayingSound(this);

Hope it will help you.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top