java - Sound not replaying on onTouchListener -
so have button that, when held, play sound. however, not seem "reset" , never plays sound again when hold down button again.
e/mediaplayer﹕ start called in state 0 e/mediaplayer﹕ error (-38, 0)
error in log when try hold button down again. here code:
@override protected void oncreate(bundle savedinstancestate) { final mediaplayer bark = mediaplayer.create(this, r.raw.bark); super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); playsound = (button) findviewbyid(r.id.btn); playsound.setontouchlistener(new view.ontouchlistener() { @override public boolean ontouch(view v, motionevent event) { switch (event.getaction()) { case motionevent.action_down: if(!bark.isplaying()) bark.start(); break; case motionevent.action_up: if(bark.isplaying()) bark.stop(); break; } return true; } }); }
instead of calling start/stop can call start/pause seekto()
:
case motionevent.action_down: if(!bark.isplaying()) bark.start(); break; case motionevent.action_up: if(bark.isplaying()){ bark.pause(); bark.seekto(0); } break;
if want use start/stop, make sure call prepare() before calling start() again.
the reason why code isn't working because according state diagram stop() stops playing , puts mp in stopped state. before starting play next time, should call prepare() , start() again.
edit : place music file in assets folder , use file descriptor. way can reset mp , replay:
using start/stop:
@override protected void oncreate(bundle savedinstancestate) { assetmanager assetmanager=context.getassets(); assetfiledescriptor filedescriptor = assetmanager.openfd("bark.mp3"); //replace right extension super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); playsound = (button) findviewbyid(r.id.btn); playsound.setontouchlistener(new view.ontouchlistener() { @override public boolean ontouch(view v, motionevent event) { switch (event.getaction()) { case motionevent.action_down: if(!bark.isplaying()){ bark.reset(); bark.setdatasource(filedescriptor.getfiledescriptor()); bark.prepare(); bark.start(); } break; case motionevent.action_up: if(bark.isplaying()) bark.stop(); break; } return true; } }); }
Comments
Post a Comment