[英]android: how to play sound in android on button click from a separate class
我是Java和android的新手,我想通过不同的按钮单击在我的应用程序中播放声音,为此,我制作了一个单独的类来播放声音,但无法使其正常工作。我想调用此类并播放声音当用户单击按钮时。 任何人都可以帮助如何为媒体播放器创建单独的类,然后单击按钮即可调用它。
我声明媒体播放器的类的代码
public class CorrectSound extends Activity implements OnPreparedListener{
public static void playSound(Context context){
MediaPlayer mp = MediaPlayer.create(context, R.raw.tiktik);
mp.setOnPreparedListener(null);
}
@Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.start();
}
}
这是在单独活动中的按钮,我想在这里调用此类。
public void optionAClick (View V){
Intent i = new Intent(Login.this,profile.class);
startActivity(i);
}
好的,删除playSound函数中的所有内容,并输入以下内容:
public static void playSound(Context context){
MediaPlayer mp = MediaPlayer.create(context, R.raw.tiktik);
mp.start();
}
现在,无论何时调用函数,它都会发出声音。
在一个类中创建一个静态函数,然后从所需的任何类中调用它。
例
public class MyApplication extends Application {
......
......
public static PlaySound(Context context){
MediaPlayer mp = MediaPlayer.create(context, R.raw.notif);
mp.start();
}
}
从其他班级
只需使用此:
MyApplication.PlaySound(this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.