performance - android : play short sound with short evoluting period using SoundPool -
i want implement sort of radar can find on cars parking. on service correctly connected activity binder, start thread must repeat short sound.wav (110ms long) short period change. code, @ beginning first loop plays sound has difficulties , lose rythm. worst, service never stop. garbage collector saturated. didn't find way realise this. thx
public class mainservice extends service implements onloadcompletelistener{ private boolean soundradarloaded; private soundpool spoolradar; private int soundradarid; private thread timerthread; private boolean timerthreadrunning; public int onstartcommand(intent intent, int flags, int startid) { soundradarloaded=false; spoolradar = new soundpool(10, audiomanager.stream_music, 0); soundradarid = spoolradar.load(this, r.raw.beepradar1, 1); spoolradar.setonloadcompletelistener(this); timerthreadrunning=true; timerthread=new thread(new runnable() { @override public void run() { int counter=0; long offset=system.currenttimemillis(); while(timerthreadrunning) { // traitement longtime=system.currenttimemillis()-offset; if(soundradarloaded && longtime%400==0){//play every 400ms spoolradar.play(soundradarid, 1, 1, 1, 0, 1f); } try { thread.sleep(1); } catch (interruptedexception ex) { } } } }); timerthread.start(); } @override public void onloadcomplete(soundpool arg0, int arg1, int arg2) { if(arg0==spoolradar) soundradarloaded=true; } @override public void onstop() { timerthreadrunning=false; try{ thread.sleep(1); }catch (interruptedexception ex) { } spoolradar.release(soundradarid); } }
precision of thread.sleep() isn't guaranteed. if thread.sleep(1) ignored line
if(soundradarloaded && longtime%400==0){//play every 400ms
may executed multiple times during same millisecond , multiple audio streams played @ same time (or @ undesired time later). second problem timerthread running , using cpu (and battery) time.
look @ https://developer.android.com/reference/java/util/timer.html or maybe https://developer.android.com/reference/java/util/concurrent/scheduledthreadpoolexecutor.html better solution.
Comments
Post a Comment