audio - Android play sounds on device input -


hi i'm relatively new android programming. i'm doing project requires me develop app connect device has 8 buttons.

the device connected android phone via bluetooth

android phone = samsung galaxy s4

android version = 5.0.1

api = 21

so device, when user presses on button, bluetooth data sent, read , displayed 0 on main ui.

1 = button not pressed. 0 = button pressed.

so labeled pins.

pin 1 [0] -> button on device pressed

pin 2 [1]

pin 3 [1]

pin 4 [1]

pin 5 [1]

pin 6 [1]

pin 7 [1]

pin 8 [1]

so problem is, need produce sound when button clicked.

public class mainactivity extends sherlockfragmentactivity {

private drawerlayout drawerlayout; private listview drawerlist; private actionbardrawertoggle drawertoggle; private menuitem startrecord, stoprecord;  private charsequence title; private charsequence drawertitle;    private string[] navtitles; private typedarray navicons;     private arraylist<navdraweritem> draweritems; private navdrawerlistadapter adapter;  public static sharedpreferences sp; private device device; private list<integer> buttonpins; private sparsearray<pin> pins;   private timer timer; private timer mytimer; private timertask timertask; private timertask mytimertask; private boolean timerflag; private int timeout = 3000; private progressdialog progress;  public static int position = 0; private boolean active;  public static final int message_state_change = 1; public static final int message_read = 2; public static final int message_device_name = 3; public static final int message_toast = 4; private static final boolean d = true; private static final string tag = "musicfragment"; private string mconnecteddevicename = null; public static final string device_name = "device_name"; public static final string toast = "toast"; private bluetoothadapter mbluetoothadapter; private static final int request_connect_device = 1; private static final int request_enable_bt = 2; private btservice mbtservice = null;  public textview btmsgtxt; public uri uriinstrument; public imageview imginstrument; public bootstrapbutton btnreconnect; public bootstrapbutton btnreselect;  soundpool instrumentsound; int recorder1; int recorder2; int recorder3; int recorder4; int recorder5; int recorder6; int recorder7; int recorder8; int saxophone1; int saxophone2; int saxophone3; int saxophone4; int saxophone5; int saxophone6; int saxophone7; int saxophone8; int bell;  private pininfo mpininfo; private instrumentsensor minstrumentsensor; private harpplayer mharpplayer; private recorderplayer mrecorderplayer; private saxophoneplayer msaxophoneplayer; private bellplayer mbellplayer;   private soundfileplayer mplayer; private boolean misplaying; private instrumentsoundfiles minstrumentsoundfiles; private arraylist<integer> currentinstruments; timer mtimer; private boolean mistimerrunning; timertask retrievepininfotask;      @override protected void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.activity_main);      sp = preferencemanager.getdefaultsharedpreferences(this);      mbluetoothadapter = bluetoothactivity.mbluetoothadapter;      btmsgtxt = (textview)findviewbyid(r.id.tv_btmsg);     imginstrument = (imageview)findviewbyid(r.id.iv_instrument);     btnreconnect = (bootstrapbutton) findviewbyid(r.id.btn_reconnect);     btnreselect = (bootstrapbutton) findviewbyid(r.id.btn_reselect);     loadsound();      btnreconnect.setonclicklistener(new view.onclicklistener() {         @override         public void onclick(view view) {             mbtservice = null;             startbtservice();         }      });     btnreselect.setonclicklistener(new view.onclicklistener()     {         @override         public void onclick(view view)         {             intent = new intent(mainactivity.this,bluetoothactivity.class);             startactivity(i);             finish();         }      });     //ui side drawer     drawerlayout = (drawerlayout) findviewbyid(r.id.drawer_layout);     drawerlist = (listview) findviewbyid(r.id.left_drawer);     navtitles = getresources().getstringarray(r.array.drawer_titles);     navicons = getresources().obtaintypedarray(r.array.drawer_icons);      title = drawertitle = gettitle();     // set custom shadow overlays main content when drawer opens     drawerlayout.setdrawershadow(r.drawable.drawer_shadow, gravitycompat.start);      // set drawer's list view items , click listener     draweritems = new arraylist<navdraweritem>();     draweritems.add(new navdraweritem(navtitles[0], navicons.getresourceid(0, -1))); // music            draweritems.add(new navdraweritem(navtitles[1], navicons.getresourceid(1, -1))); // profile     draweritems.add(new navdraweritem(navtitles[2], navicons.getresourceid(2, -1))); // setting     draweritems.add(new navdraweritem(navtitles[3], navicons.getresourceid(3, -1))); // guide     navicons.recycle();      adapter = new navdrawerlistadapter(getapplicationcontext(), draweritems);     drawerlist.setadapter(adapter);     drawerlist.setonitemclicklistener(new draweritemclicklistener());      // enable actionbar app icon behave action toggle nav drawer     getsupportactionbar().setdisplayhomeasupenabled(true);     getsupportactionbar().sethomebuttonenabled(true);       // actionbardrawertoggle ties the proper interactions between sliding drawer , action bar app icon     drawertoggle = new actionbardrawertoggle(this, /* host activity */ drawerlayout, /* drawerlayout object */         r.drawable.icon_drawer, /* nav drawer image replace 'up' caret */         r.string.drawer_open, /* "open drawer" description accessibility */         r.string.drawer_close /* "close drawer" description accessibility */     ) {         public void ondrawerclosed(view view) {             getactionbar().settitle(title);             invalidateoptionsmenu(); // creates call onprepareoptionsmenu()         }          public void ondraweropened(view drawerview) {             getactionbar().settitle(drawertitle);             invalidateoptionsmenu(); // creates call onprepareoptionsmenu()         }     };     drawerlayout.setdrawerlistener(drawertoggle);      if (savedinstancestate == null) {         selectitem(0);     }      mainactivity.this.setvolumecontrolstream(audiomanager.stream_music);      minstrumentsoundfiles = ((ninjatrackapplication)getapplication()).getinstrumentsoundfiles();     minstrumentsensor = new instrumentsensor(minstrumentsoundfiles);     misplaying = false;     mplayer = null;     currentinstruments = new arraylist<integer>(); }   @override protected void onresume() {     startbtservice();     super.onresume(); }  @override protected void onstart() {     super.onstart();     startbtservice();     active = true;  }  private void startbtservice() {     // if bt not on, request enabled.     // setupbtconnsession() called during onactivityresult     if (mbluetoothadapter != null)     {         if (!mbluetoothadapter.isenabled()) {             intent enableintent = new intent(bluetoothadapter.action_request_enable);             startactivityforresult(enableintent, request_enable_bt);             // otherwise, setup bluetooth connection session         } else {             if (mbtservice == null) {                 setupbtconnsession();             }             connectme();         }     }     else     {         mbluetoothadapter = bluetoothadapter.getdefaultadapter();     } }  private void setupbtconnsession() {     log.d(tag, "setupbtconnsession()");     // initialize btservice perform bluetooth connections     mbtservice = new btservice(mhandler); }  handler mhandler = new handler() {     @override     public void handlemessage(message msg) {          switch (msg.what) {             case message_state_change:                 if(d) log.i(tag, "mhandler-message_state_change: " + msg.arg1);                 switch (msg.arg1) {                     case btservice.state_connected:                         btmsgtxt.settext("status: connected " + mconnecteddevicename + "!");                         btnreconnect.setvisibility(view.invisible);                         btnreselect.setvisibility(view.invisible);                         break;                      case btservice.state_connecting:                         btmsgtxt.settext("status: connecting!");                         uriinstrument = uri.parse("android.resource://nyp.fypj.ninjatrack/" + r.drawable.ninjatracklogo);                         imginstrument.setimageuri(null);                         imginstrument.setimageuri(uriinstrument);                         break;                     case btservice.state_listen:                     case btservice.state_none:                         uriinstrument = uri.parse("android.resource://nyp.fypj.ninjatrack/" + r.drawable.ninjatracklogo);                         imginstrument.setimageuri(null);                         imginstrument.setimageuri(uriinstrument);                          btmsgtxt.settext("status: not connected!");                         btnreconnect.setvisibility(view.visible);                         btnreselect.setvisibility(view.visible);                 }                 break;             case message_read:                 byte[] readbuf = (byte[]) msg.obj;                 analyzer pinanalyzer = new analyzer();                 string instrument = "";                 if(pinanalyzer.populatepininfo(readbuf,msg.arg1)){ //populate pins                     try {                           mpininfo = pinanalyzer.populatepin(readbuf, msg.arg1);                         if(mpininfo.figure == 4)                         {                             //saxophone                             playsaxophone();                         }                         else if(mpininfo.figure == 5)                         {                             //recorder                             playrecorder();                         }                          log.i(tag, "mhandler-message_read: " + mpininfo);                         btmsgtxt.settext("******\n" + mpininfo + "\n******");                      }                     catch(exception e)                     {                      }                 }                 break;         }     } };  private void connectme() {     string devicename = "firefly-9a97";     bluetoothdevice result = null;     set<bluetoothdevice> devices = mbluetoothadapter.getbondeddevices();     if (devices != null) {         (bluetoothdevice device : devices) {             if (devicename.equals(device.getname())) {                 result = device;                 break;             }         }     }     // attempt connect device     if (result != null)         mbtservice.connect(result); }    private void loadsound() {     new thread(new runnable() {         @override         public void run() {             instrumentsound = new soundpool(10,audiomanager.stream_music,0);             recorder1 = instrumentsound.load(mainactivity.this,r.raw.recorder1,1);             recorder2 = instrumentsound.load(mainactivity.this,r.raw.recorder2,1);             recorder3 = instrumentsound.load(mainactivity.this,r.raw.recorder3,1);             recorder4 = instrumentsound.load(mainactivity.this,r.raw.recorder4,1);             recorder5 = instrumentsound.load(mainactivity.this,r.raw.recorder5,1);             recorder6 = instrumentsound.load(mainactivity.this,r.raw.recorder6,1);             recorder7 = instrumentsound.load(mainactivity.this,r.raw.recorder7,1);             recorder8 = instrumentsound.load(mainactivity.this,r.raw.recorder8,1);              saxophone1 = instrumentsound.load(mainactivity.this,r.raw.saxophone1,1);             saxophone2 = instrumentsound.load(mainactivity.this,r.raw.saxophone2,1);             saxophone3 = instrumentsound.load(mainactivity.this,r.raw.saxophone3,1);             saxophone4 = instrumentsound.load(mainactivity.this,r.raw.saxophone4,1);             saxophone5 = instrumentsound.load(mainactivity.this,r.raw.saxophone5,1);             saxophone6 = instrumentsound.load(mainactivity.this,r.raw.saxophone6,1);             saxophone7 = instrumentsound.load(mainactivity.this,r.raw.saxophone7,1);             saxophone8 = instrumentsound.load(mainactivity.this,r.raw.saxophone8,1);              bell = instrumentsound.load(mainactivity.this, r.raw.bell,1);         }     }).start(); }  private void playrecorder() {      new thread(new runnable() {         @override         public void run() {             try {                      if (mpininfo.btn1 == 0) {                         instrumentsound.play(recorder1, 1, 1, 1, 0, 1);                     }                     if (mpininfo.btn2 == 0) {                         instrumentsound.play(recorder2, 1, 1, 1, 0, 1);                     }                     if (mpininfo.btn3 == 0) {                         instrumentsound.play(recorder3, 1, 1, 1, 0, 1);                     }                     if (mpininfo.btn4 == 0) {                         instrumentsound.play(recorder4, 1, 1, 1, 0, 1);                     }                     if (mpininfo.btn5 == 0) {                         instrumentsound.play(recorder5, 1, 1, 1, 0, 1);                     }                     if (mpininfo.btn6 == 0) {                         instrumentsound.play(recorder6, 1, 1, 1, 0, 1);                     }                     if (mpininfo.btn7 == 0) {                         instrumentsound.play(recorder7, 1, 1, 1, 0, 1);                     }                     if (mpininfo.btn8 == 0) {                         instrumentsound.play(recorder8, 1, 1, 1, 0, 1);                     }             }              catch (exception ex) {              }         }     }).start();  }  private void playbell(final pininfo pi) {      new thread(new runnable() {         @override         public void run() {             try {                 if(pi.accx > 30)                 {                  }             }              catch (exception ex) {              }         }     }).start();  }  private void playsaxophone() {     new thread(new runnable() {         @override         public void run() {             try {                 if (mpininfo.btn1 == 0) {                     instrumentsound.play(saxophone1, 1, 1, 1, 0, 1);                 }                 if (mpininfo.btn2 == 0) {                     instrumentsound.play(saxophone2, 1, 1, 1, 0, 1);                 }                 if (mpininfo.btn3 == 0) {                     instrumentsound.play(saxophone3, 1, 1, 1, 0, 1);                 }                 if (mpininfo.btn4 == 0) {                     instrumentsound.play(saxophone4, 1, 1, 1, 0, 1);                 }                 if (mpininfo.btn5 == 0) {                     instrumentsound.play(saxophone5, 1, 1, 1, 0, 1);                 }                 if (mpininfo.btn6 == 0) {                     instrumentsound.play(saxophone6, 1, 1, 1, 0, 1);                 }                 if (mpininfo.btn7 == 0) {                     instrumentsound.play(saxophone7, 1, 1, 1, 0, 1);                 }                 if (mpininfo.btn8 == 0) {                     instrumentsound.play(saxophone8, 1, 1, 1, 0, 1);                 }             }              catch (exception ex) {              }         }     }).start();  }    @override protected void onstop() {     super.onstop();     //instrumentsound.release();     active = false; } 

when sound comes it, plays fine has bit of distortion. not clear.

as need sounds produced similar instrument, sounds must continuous, if playing recorder/saxophone.

the sounds must mix, example if press 2 buttons @ same time, audio must mixed.

i need tips/advice. thank you

if want use short sounds , want them mixed, soundpool correct thing. @ video on youtube, -https://www.youtube.com/watch?v=l8gejqgcy28 has built similar. , distortion - try lower sample rate.


Comments