android - Trying to implement button click sound with MediaPlayer crashes -


i have custom view (a button) , want have sound when pressed.

private void playsound() {     if (mediaplayer == null)         initmediaplayer();      try {         if (mediaplayer.isplaying())             mediaplayer.stop();         mediaplayer.prepare();         mediaplayer.start();     } catch (ioexception e) {         e.printstacktrace();     } catch (illegalstateexception e) {         e.printstacktrace();     } }  private void initmediaplayer() {     try {         assetfiledescriptor afd = getcontext().getassets().openfd("music/number_tap.m4a");         mediaplayer = new mediaplayer();         mediaplayer.setdatasource(afd.getfiledescriptor(), afd.getstartoffset(), afd.getlength());     } catch (ioexception e) {         e.printstacktrace();     } } 

i call playsound method every time button clicked. works long there 1 button on screen. no problem @ all.

it crashes if have more buttons on screen , press first button couple of times (works) , other button 2 times (crashes on second press of second button).

any idea wrong? here's crash stacktrace.

fatal exception: main process: com.matejhacin.multiflow, pid: 20991 java.lang.illegalstateexception @ android.media.mediaplayer._prepare(native method) @ android.media.mediaplayer.prepare(mediaplayer.java:1163) @ com.matejhacin.multiflow.views.keybuttonview.playsound(keybuttonview.java:126) @ com.matejhacin.multiflow.views.keybuttonview.ontouch(keybuttonview.java:77)

from can see, have own implementation of button keybuttonview.java, , in class have mediaplayer member variable, when have 2 buttons, respectively have 2 instances of keybuttonview class , 2 instances of mediaplayer. why don't use 1 instance of mediaplayer, let's make static, , make playsound() , initmediaplayer() methods synchronized , static, should quick , simple change, test if there issue. , else, use ontouch() handle click, why don't try onclicklistener? if not use ontouch end bunch of calls on ui thread, , each blocking @ prepare(), not good. once fix issue, should consider rewrite prepareasync() , setonpreparedlistener().


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -