button - How to add soundButton(on&off) on a activity in android apps? -
i have created branch activity .now wanted add 2 button on branch activity. when click on 'sound on' button beep sound on start , when clicked on 'sound off' beep sound off. , hide simultaneously.
thank's
my code on activity
@override protected void oncreate(bundle savedinstancestate) { // todo auto-generated method stub super.oncreate(savedinstancestate); setcontentview(r.layout.sound_layout); soundbttnon =(button) findviewbyid(r.id.soundbttnon); soundbttnon.setonclicklistener( new onclicklistener(){ @override public void onclick(view v) { startmediaplayer(); } } ); soundbttnoff =(button) findviewbyid(r.id.soundbttnoff); soundbttnoff.setonclicklistener( new onclicklistener(){ @override public void onclick(view v) { stopmediaplayer(); } } ); } private void startmediaplayer() { mediaplayer = mediaplayer.create(soundlayout.this,r.raw.keybutton5); mediaplayer.start(); } private void stopmediaplayer() { if( mediaplayer != null ) { mediaplayer mp = null; mp.stop(); mp.release(); } }
it showing no problem not working too..:p..i not able implement sound.
you can simple google search find tons of samples adding button. playing sound file check out mediaplayer class.
button startbtn, stopbtn; //get reference of button .... final mediaplayer mp = new mediaplayer(); startbtn.onclicklistener() { public void onclick(view v) { try { mp.setdatasource(path+"/"+audio.mp3); mp.prepare(); mp.start(); } catch (exception e) { e.printstacktrace(); } } }; stopbtn.onclicklistener() { public void onclick(view v) { if(mp.isplaying()) { mp.stop(); //hide buttons stopbtn.setvisibiltiy(view.gone); startbtn.setvisibility(view.gone); } } };
ps: on , off, don't need 2 buttons, 1 button.
edit:
for single button, use playing state of media player deciding action take on button click.
singlebtn.onclicklistener() { public void onclick(view v) { try { if(mp.isplaying()) mp.stop(); else { mp.setdatasource(path+"/"+audio.mp3); mp.prepare(); mp.start(); } } catch (exception e) { e.printstacktrace(); } } };
Comments
Post a Comment