我在Activity上实现了切换Botton。我想在该按钮上添加声音(打开和关闭),但无法在其上添加声音。
这是我编写的代码。
public class SoundLayout extends Activity implements OnClickListener
{
Button soundBttnOn;
private String _showText;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sound_layout);
/** Fetched from the MAIN ACTIVITY */
Bundle bundle = getIntent().getExtras();
if(bundle!=null){
_showText = bundle.getString("button_click");
}
Log.i("btnClick","button clicked is :"+_showText);
soundBttnOn = (Button) findViewById(R.id.togglebutton);
soundBttnOn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
/** make a refernce to store the intent when the view has been clicked*/
Intent intent;
/** Make cases according to the number of buttons you have in screen
* In this case, I've added one.*/
switch(view.getId()){
case R.id.togglebutton :
Log.i("btnClick","Result button is clicked whose id is :"+view.getId());
/** Intent should be fired from this activity to the other activity*/
intent = new Intent(SoundLayout.this, Main.class);
/** Start the intent
* startActivity(intent);
this.finish();*/
break;
}
}
}
这里我试图在切换按钮上添加声音,但是我无法在其上添加声音功能。因此,当我单击“声音打开”时,它被激活,而当我单击“声音关闭”时,它被禁用。
您可以使用切换按钮的setOnCheckedChangeListener。在这种情况下,您将获得一个参数,指示按钮处于打开还是关闭状态。基于此,您可以使用媒体播放器播放所需的声音。
ToggleButton tb = (ToggleButton) findViewById(R.id.toggleButton);
tb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
System.out.println("ischecked>>>>>>>>>>>>>>>>>>>>>>>>>.");
else
System.out.println("not checked>>>>>>>>>>>>>>>>>>>>>>>>>.");
}
});
只需将声音文件放在/ res / raw中(在创建文件夹之后),然后使用MediaPlayer初始化,启动然后停止播放声音。
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.AudioFile1); mp.start();
然后您从mp。获得所有的开始/停止/重置/暂停/释放方法。
public void togglesound(View v) {
int play;
boolean on = ((ToggleButton) v).isChecked();
if (on) {
play = 1;
// Enable sound
if (play == 1) {
cleanUpMediaPlayer();
Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(10000);//TIME TO VIBRATE
mp = MediaPlayer.create(this, R.raw.musicmachine);
mp.start();
} else {
play = 0;
// Disable sound
stopMediaPlayer();
}
}
}
// Cleans MediaPlayer
public void cleanUpMediaPlayer() {
if (mp != null) {
try {
mp.stop();
mp.release();
mp = null;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(Displayone.this, "Error", Toast.LENGTH_LONG).show();
}
}
}
@Override
protected void onPause() {
super.onPause();
stopMediaPlayer();
}
public void stopMediaPlayer()
{
mp.stop();
}