0

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.

4

2 回答 2

2

您只能在测试类中指定 mediaPlayer,然后从测试类中调用涉及 mediaPlayerSettings 的方法。测试类本身无法播放,因为它不扩展活动。

但是,如果您想从类测试中获取方法,请这样做:

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;
         }
     }

}

因此在 Activity 中这样称呼它:

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

希望它会帮助你。

于 2013-07-28T15:08:54.970 回答
1

您必须将您的转发Context到构造函数中的类。

为您添加一个班级成员Context

Context mContext;

然后,添加一个接受 a 的构造函数Context

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

使用此构造函数实例化您的类:

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

最后,如果您想在课堂上播放声音,请mContext使用Context

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

如果您想在 FrameLayout 中实例化您的类,请使用以下代码:

Test test = new Test(getContext()); //Assuming you call this in a subclass of FrameLayout
于 2013-07-28T15:04:12.490 回答